Two Pointers · 174Easy
Reverse String
Write a function that reverses an array of characters s IN PLACE. Do not return anything; modify s directly using O(1) extra memory.
Constraints
- 1 <= s.length <= 10^5
- s[i] is a printable ASCII character.
Examples
reverseString(["h", "e", "l", "l", "o"]) -> s becomes ["o", "l", "l", "e", "h"] reverseString(["H", "a", "n", "n", "a", "h"]) -> s becomes ["h", "a", "n", "n", "a", "H"] reverseString(["a"]) -> s becomes ["a"] // single character, unchanged reverseString(["a", "b"]) -> s becomes ["b", "a"] // one swap reverseString(["x", "y", "z"]) -> s becomes ["z", "y", "x"] // odd length: the middle stays put reverseString(["7", "7", "7"]) -> s becomes ["7", "7", "7"] // all same, visibly unchanged
Edge cases
- A single character is unchanged.
- Odd length: the middle character stays put.
Show the target complexity (spoiler)
- Naive
- O(n) time, O(n) space — build a reversed copy and write it back (breaks the rule).
- Target
- O(n) time, O(1) space — swap s[l] and s[r], moving both pointers inward.
Solve it
By hand, in your editor. The runner checks answers and timing.
git clone https://github.com/sarmadkung/optimal-round cd optimal-round # open problems/02-two-pointers/174-reverse-string.js ./practice c 174