Reverse String
Easy
Topics
Given a string s, return the string reversed.
Example 1
in
out
It must happen in place, so building a reversed copy does not count.
Rows are the string before and after reversal.
Input: s = "hello" Output: "olleh"
Example 2
in
out
Input: s = "abcd" Output: "dcba"
Constraints
- 1 <= s.length <= 10^5
- s consists of printable ASCII letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Reversing is a two-pointer swap: exchange the ends and walk inward until the pointers meet. Each character moves exactly once and nothing is allocated.
The shown one-liner s[::-1] is clear and idiomatic in Python, but it builds a new string. That matters because the canonical form of this problem asks you to modify a character array in place with O(1) extra space — which is exactly what the two-pointer version delivers and the slice does not.
Approach
left = 0,right = n - 1.- While
left < right: swap, then move both inward.
Dry Run
['h','e','l','l','o']
left=0 right=4 swap h/o ['o','e','l','l','h']
left=1 right=3 swap e/l ['o','l','l','e','h']
left=2 right=2 pointers meet, stop
answer "olleh"
note the middle character of an odd-length string is
never swapped, which is correct -- it is already in placeComplexity
- Time — O(n): n/2 swaps.
- Space — O(1) for the two-pointer version. The
s[::-1]form shown is O(n) because it allocates the result — and Python strings are immutable, so a genuinely in-place reverse requires a list of characters. Worth stating plainly rather than claiming O(1) for a slice.
Common Pitfalls
- Looping to
nrather than stopping at the midpoint, which swaps every pair twice and returns the original string. - Using
left <= right, which pointlessly swaps the middle element with itself — harmless here, but a sign the invariant is not clear. - Claiming O(1) space for a slice or for
"".join(reversed(s)); both allocate. - Reversing a Python string in place. They are immutable; convert to a list first.
Full Solution — all languages
class Solution:
def reverseString(self, s):
return s[::-1]import java.util.*;
class Solution {
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string reverseString(string s) {
reverse(s.begin(), s.end());
return s;
}
};/**
* @param {string} s
* @return {string}
*/ var reverseString = function(s) {
return s.split('').reverse().join('');
};