easyleetcodeNot Started

Reverse String

A curated StudyFlow practice problem with comprehensive editorial and multi-language solutions.

Solve on leetcode
Lesson

Problem Statement

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Explanation: The characters are reversed in place.

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Explanation: The characters are reversed in place.

Constraints:

  • 1 <= s.length <= 105
  • s[i] is a printable ascii character.

What You'll Learn

Key principles and algorithmic techniques you will master from this problem:

  • Master converging two pointers for in-place array modification.
  • Perform symmetric element swaps in O(1) space.
  • Prevent index out-of-bounds errors on edge case inputs.

Pattern Recognition Trigger

How to instantly recognize this algorithmic pattern when encountering unseen interview questions:

Signals to Look For:

  • Reversing linear sequences in-place without extra buffer allocations.
  • Symmetric element pairing.

Algorithmic Decision Tree:

  • Reversing linear sequences in-place without extra buffer allocations.
  • Symmetric element pairing.

Connected Patterns:

Reverse Words in a StringValid PalindromeReverse Linked List

1. Auxiliary Array Allocation

Intuition

Create an auxiliary array of size N. Copy characters from s into the new array in reverse order, then overwrite s with the contents of the auxiliary array.

When to apply: Basic baseline comparison.

Algorithm

  1. Create temporary array temp of size n.
  2. For i from 0 to n - 1: temp[i] = s[n - 1 - i].
  3. For i from 0 to n - 1: s[i] = temp[i].

Auxiliary Array Allocation Trace

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [h, e, l, l, o]
Current operationSTEP 1 OF 6
Observation: Allocate a new array aux of length 5
Visual state
Values and pointers at this exact step
array
S
h
e
l
l
o
0
1
2
3
4
Variables at this step
Copied
'o'
From
4
To
0
Check / comparison
Allocate aux array of size 5. Copy s[4]='o' to aux[0].
Decision / next transition
Begin copying original array backwards into auxiliary buffer.
Why this step matters

Observation: Allocate a new array aux of length 5.

Decision: Copy the last element s[4]='o' into aux[0].

Invariant: First element of reversed array established.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <vector>
3
4class Solution {
5public:
6 void reverseString(std::vector<char>& s) {
7 int n = s.size();
8 std::vector<char> temp(n);
9 for (int i = 0; i < n; ++i) {
10 temp[i] = s[n - 1 - i];
11 }
12 for (int i = 0; i < n; ++i) {
13 s[i] = temp[i];
14 }
15 }
16};
17
18int main() {
19 Solution sol;
20 std::vector<char> s = {'h','e','l','l','o'};
21 sol.reverseString(s);
22 for (char c : s) std::cout << c << " "; // o l l e h
23 std::cout << std::endl;
24 return 0;
25}

Time & Space Complexity

  • Time complexity: O(N) — Performs 2N copy assignments and allocates an N-element array.
  • Space complexity: O(N) auxiliary space

Why Brute Force Doesn't Scale:

Converging two pointers performs minimal N / 2 operations.

Strict O(1) auxiliary space modifying the input array in-place.


2. Recursive In-Place Reversal

Intuition

Define helper solve(left, right). Base case: if left >= right, return. Otherwise, swap s[left] and s[right], and recurse on solve(left + 1, right - 1).

When to apply: When exploring recursive divide-and-conquer formulations.

Algorithm

  1. Helper helper(s, left, right):
  2. If left >= right: return.
  3. Swap s[left] and s[right].
  4. helper(s, left + 1, right - 1).
  5. Call helper(s, 0, s.length - 1).

Recursive In-Place Reversal Call Stack Trace

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [h, e, l, l, o]
Current operationSTEP 1 OF 6
Observation: Frame 1: helper(0, 4)
Visual state
Values and pointers at this exact step
array
S
h
e
l
l
o
0
↑ l=0
1
2
3
4
↑ r=4
Variables at this step
Frame
helper(0, 4)
Call Stack Depth
1
Swap
'h' <-> 'o'
Check / comparison
Call helper(l=0, r=4). Swap s[0] ('h') with s[4] ('o').
Decision / next transition
Swap outermost characters. Recurse inward on helper(l=1, r=3).
Why this step matters

Observation: Frame 1: helper(0, 4). Swap s[0] and s[4].

Decision: Elements swapped: s[0]='o', s[4]='h'. Push next frame helper(1, 3) to call stack.

Invariant: Outer boundaries reversed.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5class Solution {
6 void helper(std::vector<char>& s, int left, int right) {
7 if (left >= right) return;
8 std::swap(s[left], s[right]);
9 helper(s, left + 1, right - 1);
10 }
11public:
12 void reverseString(std::vector<char>& s) {
13 helper(s, 0, (int)s.size() - 1);
14 }
15};
16
17int main() {
18 Solution sol;
19 std::vector<char> s = {'h','e','l','l','o'};
20 sol.reverseString(s);
21 for (char c : s) std::cout << c << " "; // o l l e h
22 std::cout << std::endl;
23 return 0;
24}

Time & Space Complexity

  • Time complexity: O(N) — Recursion depth is N / 2, each level performing O(1) swap.
  • Space complexity: O(N) recursion call stack

3. Two Pointers In-Place Swapping (Optimal)

Intuition

Initialize pointer left = 0 and pointer right = s.length - 1. While left < right, swap s[left] and s[right], then increment left++ and decrement right--.

When to apply: The standard gold standard solution for memory-optimal in-place array reversal.

Algorithm

  1. Initialize left = 0, right = s.length - 1.
  2. While left < right:
  3. Swap s[left] and s[right].
  4. left++
  5. right--

In-Place Two-Pointer Convergence Swap

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [h, e, l, l, o]
Current operationSTEP 1 OF 6
Observation: Pointers initialized at both extremities: L = 0 ('h') and R = 4 ('o')
Visual state
Values and pointers at this exact step
array
S
h
e
l
l
o
0
↑ L=0 ('h')
1
2
3
4
↑ R=4 ('o')
Variables at this step
L Pointer
0 ('h')
R Pointer
4 ('o')
Action
Swap 'h' <-> 'o'
Check / comparison
Swap s[0] ('h') with s[4] ('o'). Advance L to 1, R to 3.
Decision / next transition
Perform swap: s[0]='o', s[4]='h'.
Why this step matters

Observation: Pointers initialized at both extremities: L = 0 (h) and R = 4 (o).

Decision: Swap elements: s[0] becomes 'o', s[4] becomes 'h'. Advance L++ and R--.

Invariant: Outer boundary reversed in O(1) memory.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5class Solution {
6public:
7 void reverseString(std::vector<char>& s) {
8 int left = 0, right = (int)s.size() - 1;
9 while (left < right) {
10 std::swap(s[left++], s[right--]);
11 }
12 }
13};
14
15int main() {
16 Solution sol;
17 std::vector<char> s = {'h','e','l','l','o'};
18 sol.reverseString(s);
19 for (char c : s) std::cout << c << " "; // o l l e h
20 std::cout << std::endl;
21 return 0;
22}

Time & Space Complexity

  • Time complexity: O(N) strictly — Performs exactly N / 2 swaps with zero extra memory allocations.
  • Space complexity: O(1) extra space

Approach Comparison Matrix

Side-by-side comparison of time, space, and algorithmic trade-offs across each approach:

ApproachTimeSpaceCore IdeaTrade-off / Bottleneck
1.Auxiliary Array CopyO(N)O(N)Simple copy in reverse order.Violates O(1) in-place memory constraint.
2.Recursive Divide and ConquerO(N)O(N) recursion stackDemonstrates recursion.Consumes O(N) call stack memory.
3.Two Pointers In-Place Swapping (Optimal)OptimalO(N)O(1) extra spaceStrictly optimal, zero auxiliary space, N / 2 swaps.None.

Common Pitfalls & Crucial Edge Cases

Pitfall 1:

Using <= in while condition which performs an unnecessary self-swap at the midpoint.

Pitfall 2:

Returning a new array instead of modifying in-place.

Crucial Edge Cases to Validate:

  • Single character array (s = [a]): left = 0, right = 0; loop condition left < right is false immediately, array remains [a].
  • Even length array (s = [a,b]): Single swap occurs, pointers cross with left=1, right=0, terminating cleanly.
  • Palindrome array (s = [r,a,c,e,c,a,r]): Swaps symmetric identical characters in-place correctly.

Interview Tips & Best Practices

How to communicate your thought process and address follow-ups in a live technical interview:

  1. Emphasize that the question specifically requires in-place modification.
  2. Demonstrate clean two-pointer while loop.

Quick Comprehension Check

Test your intuitive understanding of the core concept in 30 seconds:

1.How many swap operations are executed to reverse an array of length N in-place?