291. Reverse String
You are given a piece of text as an array of characters s. Reverse the order of the characters and return the array.
The interview version comes with a catch: do it in place, using O(1) extra memory — no second array, no building a new string. The classic move is to swap your way inward from both ends with two pointers.
Your function receives the character array (in Python, a list of single-character strings) and returns it with the characters in reverse order.
Example 1:
Input: s = ['h','e','l','l','o']
Output: ['o','l','l','e','h']
Explanation: Swapping ends inward: h↔o, then e↔l, and the middle l stays put.
Example 2:
Input: s = ['H','a','n','n','a','h']
Output: ['h','a','n','n','a','H']
Explanation: Case is preserved — characters move, they don't change.
Constraints:
- 1 ≤ s.length ≤ 10⁵
- s consists of printable ASCII characters (no whitespace)
- Target: O(1) extra memory — reverse in place
Hints:
Reversing means the character at index i ends up at index n − 1 − i. Reading the array backwards into a fresh array does it — but uses O(n) extra space.
Keep two indices, left starting at 0 and right at n − 1. Swap the pair, move both inward, and stop as soon as left >= right — every element is touched once and no scratch array is needed.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = ['h','e','l','l','o']
Expected output: ['o','l','l','e','h']