Reverse String(#344)

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"]

Explanation:

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

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

Explanation:

๐Ÿง  Approach

Approach โ€“ Two Pointer In-place:**

We solve this using the two-pointer approach. Initialize one pointer at the start (`left = 0`) and the other at the end (`right = s.length - 1`). Swap the characters at these positions and move the pointers toward each other until they meet. This approach reverses the array in-place without using extra space.

**Note:** A brute force method using a new array is possible, but it violates the problem constraint of O(1) extra space.

๐Ÿ’ป Code

// ๐Ÿ”น 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