Reverse String

Easytwo-pointersstring
Category: Fundamentals
Companies that ask this question:
AmazonMicrosoftGoogle

Approach

Reverse String

Approach

Use two pointers technique to swap characters from both ends moving toward the center.

Algorithm

  1. Initialize left pointer at start (0) and right pointer at end (n-1)
  2. While left < right:
    • Swap characters at left and right positions
    • Move left pointer forward
    • Move right pointer backward
  3. Process completes when pointers meet in the middle

Complexity

  • Time: O(n) - single pass through half the array
  • Space: O(1) - in-place modification, no extra space

Key Insights

  • Two-pointer technique is optimal for in-place reversal
  • Only need to process half the array
  • Works for both even and odd length arrays

Solution

java
1class Solution {
2    public void reverseString(char[] s) {
3        int left = 0, right = s.length - 1;
4        
5        while (left < right) {
6            char temp = s[left];
7            s[left] = s[right];
8            s[right] = temp;
9            left++;
10            right--;
11        }
12    }
13}
Loading visualizer...