Sobes.tech
Junior — Middle

How can the sequence of characters be most effectively reversed?

sobes.tech AI

Answer from AI

The most efficient way to reverse a string in C/C++ is to use two pointers moving towards each other, swapping characters. This operates in O(n) time and requires no additional memory.

Example in C++:

#include <iostream>
#include <cstring>

void reverseString(char* str) {
    int left = 0;
    int right = strlen(str) - 1;
    while (left < right) {
        std::swap(str[left], str[right]);
        left++;
        right--;
    }
}

int main() {
    char s[] = "Hello, world!";
    reverseString(s);
    std::cout << s << std::endl; // !dlrow ,olleH
    return 0;
}

This approach is efficient and simple to implement.