Reverse String — Two Pointer In-Place O(n) [Meta, Microsoft Easy]

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem Statement

Input: ['h','e','l','l','o']['o','l','l','e','h'].

Key Insight: Two pointers starting from both ends. Swap s[left] and s[right], then advance both inward until they meet. No extra space needed.

C Solution

void reverseString(char* s, int n) {
    int l = 0, r = n - 1;
    while (l < r) { char t = s[l]; s[l++] = s[r]; s[r--] = t; }
}

C++ Solution

#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    void reverseString(vector<char>& s) {
        int l = 0, r = (int)s.size() - 1;
        while (l < r) { swap(s[l++], s[r--]); }
    }
};

Java Solution

class Solution {
    public void reverseString(char[] s) {
        int l = 0, r = s.length - 1;
        while (l < r) { char t = s[l]; s[l++] = s[r]; s[r--] = t; }
    }
}

JavaScript Solution

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

Python Solution

def reverseString(s):
    left, right = 0, len(s) - 1
    while left < right:
        s[left], s[right] = s[right], s[left]
        left += 1
        right -= 1

Complexity Analysis

| O(n) time | O(1) space |

Pattern applications: Valid Palindrome, Reverse Words in String, Rotate Array (reverse 3 times), Reverse Linked List.

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro