Reverse String

Easy10 min
Given an array of characters, reverse the array in place. The function must modify the existing array rather than return a reversed copy.

For ['h', 'e', 'l', 'l', 'o'], the original array must become ['o', 'l', 'l', 'e', 'h']. Creating another array would produce the correct ordering but would not satisfy the in-place requirement.

Use the inward-moving pointer pattern from the previous lesson. left and right mark the next pair of positions to swap.

Reverse a string in place

1 / 6
Step 1 of 6.
left starts at index 0 and right starts at index 4. Together they mark the first pair to swap.

Swapping the boundary values places both characters in their final reversed positions. After the swap, move both indices inward. Every position outside the new interval is now final.

The loop needs a pair of different positions, so it continues while left < right. On an odd-length input, the pointers meet at the middle character, which already belongs in its final position. On an even-length input, they cross after the final pair is swapped. An empty or one-character input begins with no pair satisfying left < right, so the loop safely performs no work.

Why can the algorithm stop when left >= right?
1def reverse_string(chars: list[str]) -> None:
2 left = 0
3 right = len(chars) - 1
4
5 while left < right:
6 chars[left], chars[right] = chars[right], chars[left]
7 left += 1
8 right -= 1
Time: O(n)Space: O(1)

Each swap finalizes two positions, so the loop performs at most n / 2 swaps and takes O(n) time. The algorithm uses two indices and constant temporary storage, so auxiliary space is O(1).