Reverse String Solution
Write a function that reverses a string. The input is given as an array of characters s. Do it in-place with O(1) extra memory.
Problem Statement
Write a function that reverses a string in-place. The input is given as a character array s. You must do this by modifying the input array directly with O(1) extra memory.
Brute Force โ New Array O(n)
Create a new array, copy elements in reverse order, then copy back. Or use a stack: push all characters, then pop them back. Both use O(n) extra space.
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(n) โ violates O(1) constraint |
Two Pointers โ O(n) time, O(1) space
Place one pointer at position 0 and one at position nโ1. Swap the characters at both pointers, then move them inward. Repeat until they meet in the middle.
- Step 1: Set
left = 0,right = n - 1. - Step 2: While
left < right: swaps[left]ands[right]. - Step 3:
left++,right--. - Step 4: When pointers cross โ done. Array is reversed.
- Any in-place transformation that pairs the first element with the last, second with second-to-last, etc. โ use converging two pointers.
- This is the simplest and most fundamental two-pointer pattern.
- It appears in reversals, palindrome checks, and partitioning problems.
Visual Walkthrough
Trace through s = ['h', 'e', 'l', 'l', 'o']:
- Only โn/2โ = 2 swaps needed for a 5-element array. The middle element stays in place.
- For even-length arrays, all elements get swapped.
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Stack / New Array | O(n) | O(n) | Violates O(1) space constraint |
| Two Pointers โ optimal | O(n) | O(1) | n/2 swaps, one temp variable |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Single character | ['a'] | left == right immediately โ no swaps, array unchanged. |
| Two characters | ['a', 'b'] | One swap โ ['b', 'a']. Minimum case that actually reverses. |
| Palindrome | ['a', 'b', 'a'] | Reversal produces the same array. Swaps still execute, just swap same values. |
| Even length | ['a', 'b', 'c', 'd'] | n/2 = 2 swaps. No middle element left alone. |
| Odd length | ['a', 'b', 'c'] | Middle element 'b' stays. Pointers cross there. |
left <= right instead of left < right. When left equals right, swapping an element with itself is harmless but unnecessary. The correct condition is left < right โ stop when pointers meet or cross.