Reverse String
Pattern: Strings basics and frequency
Swap the first and last characters, then the second and second-to-last, moving two indexes inwards until they meet. In place, O(1) extra memory.
The problem
You are given a string as an array of characters. Reverse it in place, using O(1) extra memory. For example,
["h", "e", "l", "l", "o"] becomes ["o", "l", "l", "e", "h"].
The function name reverseString matches LeetCode. Use the link above for the exact statement and limits. The
function changes the array and returns nothing.
Think first
- Where does the first character end up? The second?
- Which pairs of positions trade places?
- When do you stop so that no pair is swapped twice?
Hints
Brute force, and why it fails
Copy the characters backwards into a new array and copy them back: O(n) time but O(n) memory. Two indexes need O(1).
The key insight
Reversing is a set of independent swaps between mirror positions. Two indexes moving inwards visit each pair exactly once.
Dry run
s = h e l l o. l starts at the first index and r at the last.
The plan
l = 0, r = n - 1
while l < r:
swap s[l], s[r]
l = l + 1; r = r - 1
Complexity
- Time
O(n)- Space
O(1)
About n / 2 swaps, and only two indexes are stored.
Edge cases
- One character: nothing to swap.
- Two characters: one swap.
- Even and odd lengths both stop correctly with
l < r.
I've built my logic, show the code
Java
class Solution {
public void reverseString(char[] s) {
for (int l = 0, r = s.length - 1; l < r; l++, r--) { // swap the two ends and move inwards
char t = s[l]; s[l] = s[r]; s[r] = t;
}
}
}C++
class Solution {
public:
void reverseString(vector<char>& s) {
for (int l = 0, r = static_cast<int>(s.size()) - 1; l < r; l++, r--) swap(s[l], s[r]); // swap ends, move in
}
};Python
class Solution:
def reverseString(self, s: list[str]) -> None:
l, r = 0, len(s) - 1
while l < r: # swap the two ends and move inwards
s[l], s[r] = s[r], s[l]
l += 1
r -= 1Common mistakes
- Looping
iover the whole array, which swaps every pair twice and changes nothing. - Building a new string and returning it, when the array itself must change.
- Using
l <= r, which harmlessly swaps the middle with itself but hints at an off-by-one habit.