sagelearnai

Reverse String

Difficulty: Easy · Pattern: Two Pointers · LeetCode #344

Reverse an array of characters s in place with O(1) extra memory. Return nothing.

Examples

text
["h","e","l","l","o"]  →  ["o","l","l","e","h"]
["A","b"]              →  ["b","A"]

Hints

  1. Swap the first and last, then move inward.

Approach

Two pointers at the ends; swap s[l] and s[r], then move them toward each other until they meet. Each element is touched once.

Complexity

Time: O(n). Space: O(1).

Python solution
def reverseString(s):
    l, r = 0, len(s) - 1
    while l < r:
        s[l], s[r] = s[r], s[l]
        l += 1; r -= 1
JavaScript solution
function reverseString(s) {
  for (let l = 0, r = s.length - 1; l < r; l++, r--) [s[l], s[r]] = [s[r], s[l]];
}