Reverse String
Write a function that reverses a list of characters. Do it in-place with O(1) extra
memory — you may not allocate a second list.
Examples
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints
1 <= len(s) <= 10^5s[i]is a printable ASCII character.
Solution
Approach — two pointers
Put one pointer at the start and one at the end. Swap the two characters, then move the pointers toward each other. Stop when they meet in the middle. Each character is touched once, and swapping is a constant-time operation, so no extra memory is needed.
Solution
def reverse_string(s: list[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
Explanation
- Why two pointers? Reversing is symmetric: the first element trades places with the last, the second with the second-to-last, and so on. Two converging pointers express exactly that pairing.
- Why
left < right(not<=)? When they meet at the same index (odd-length list), that middle character stays put — swapping it with itself is pointless. - In-place swap: Python's tuple assignment
a, b = b, aswaps without a temp variable.
Complexity
- Time:
O(n)— each character is visited once. - Space:
O(1)— only two integer indices, regardless of input size.
Interview tips
Interviewers use this to check you can reason about in-place mutation and pointer
invariants. If asked to reverse an actual str (immutable in Python), note you'd return
s[::-1] — but that allocates a new string, so it doesn't meet the O(1)-space bar.
Related problems
Group Anagrams
Medium
Contains Duplicate
Easy
Maximum Subarray
Medium
Product of Array Except Self
Medium