Reverse a String

Easy

Write a function that reverses a string in place. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.

Examples

InputOutput
s = ["h","e","l","l","o"]["o","l","l","e","h"]
s = ["H","a","n","n","a","h"]["h","a","n","n","a","H"]

Python 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

JavaScript Solution

function reverseString(s) {
  let left = 0, right = s.length - 1;
  while (left < right) {
    [s[left], s[right]] = [s[right], s[left]];
    left++;
    right--;
  }
}

Step-by-Step Explanation

  1. Use two pointers: one at the start, one at the end.
  2. Swap the characters at both pointers.
  3. Move left pointer forward and right pointer backward.
  4. Stop when the pointers meet or cross.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

StringTwo Pointers

Related Problems

Related Tools

All Problems