You're out of free questions.

Upgrade now

Write a function that takes a string and reverses the letters in place.

In general, an in-place algorithm will require swapping elements.

We swap the first and last characters, then the second and second-to-last characters, and so on until we reach the middle.

void reverse(string& str) { if (str.empty()) { return; } size_t leftIndex = 0; size_t rightIndex = str.length() - 1; while (leftIndex < rightIndex) { // swap characters swap(str[leftIndex], str[rightIndex]); // move towards middle ++leftIndex; --rightIndex; } }

time and space.

Reset editor

Powered by qualified.io

. . .