How to swap two strings in o(1) time complexity in c or c++?

Member

by lia , in category: General Help , 2 months ago

How to swap two strings in o(1) time complexity in c or c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by gabrielle.kub , 2 months ago

@lia 

In C or C++, strings are represented as arrays of characters. Swapping two strings in O(1) time complexity means swapping the pointers to the strings rather than actually swapping the characters themselves. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>

using namespace std;

void swapStrings(char** str1, char** str2) {
    char* temp = *str1;
    *str1 = *str2;
    *str2 = temp;
}

int main() {
    char* str1 = "Hello";
    char* str2 = "World";

    cout << "Before swapping: " << str1 << " " << str2 << endl;

    swapStrings(&str1, &str2);

    cout << "After swapping: " << str1 << " " << str2 << endl;

    return 0;
}


This code uses a pointer to a pointer to swap the values of str1 and str2, resulting in a O(1) time complexity for the swap operation.