Reverse String

(#344), Easy

Category: String, Two Pointer

Problem Statement

Write a function that reverses a character array in-place. You must do this by modifying the input array directly with O(1) extra memory.

Examples

Input: ["h","e","l","l","o"]

Output: ["o","l","l","e","h"]

Input: ["H","a","n","n","a","h"]

Output: ["h","a","n","n","a","H"]

Approach

Two Pointer In-place Reversal

  • Initialize two pointers: `left = 0` and `right = s.length - 1`.
  • While `left < right`, swap `s[left]` and `s[right]`.
  • Increment `left` and decrement `right` after each swap.
  • This continues until the pointers meet in the middle.
  • Note: This approach modifies the array in-place and uses no extra memory.
// 🔹 Two Pointer In-place Reversal
var reverseString = function(s) {
  let left = 0, right = s.length - 1;

  while (left < right) {
    [s[left], s[right]] = [s[right], s[left]]; // Swap using destructuring
    left++;
    right--;
  }
};

Complexity

Time: O(n)

Space: O(1)

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources