Reverse String

Easy StringTwo Pointers

Problem

Reverse a character array in place. Modify the input array, don't return a new one.

Example 1 Input: s = ['h','e','l','l','o'] Output: ['o','l','l','e','h']
Example 2 Input: s = ['H','a','n','n','a','h'] Output: ['h','a','n','n','a','H']

Constraints

Approach — Two Pointers

This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(1) extra space.

Solution code

Python

class Solution:
    def reverseString(self, s):
        return s[::-1]

Java

class Solution {
    public void reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;
        while (left < right) {
            char tmp = s[left];
            s[left] = s[right];
            s[right] = tmp;
            left++;
            right--;
        }
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Reverse String interactively → ← All solutions