Browse curriculum

Reverse String

Reverse an array of characters in place with two pointers that swap the ends and walk toward the middle.

Problem Understanding

Reverse String: reverse an array of characters in place, using O(1) extra memory.

Example: ["h", "e", "l", "l", "o"] becomes ["o", "l", "l", "e", "h"].

The Intuition: Mirror Pairs

Reversing sends the character at index i to index n − 1 − i. Those two positions simply trade places, so reversing is just swapping mirror pairs.

The classic two pointers loop walks the pairs from the outside in:

  1. l at the start, r at the end.
  2. Swap s[l] and s[r]; move l right and r left.
  3. Stop when they meet or cross.

Every character is touched once and no extra array is needed. The same swap loop reverses each block in Rotate Array.

Interactive Walkthrough

Each step swaps one mirror pair, shown filled; pairs already swapped are shaded because they are final. Try an odd and an even length to see when the pointers meet versus cross.

Dry Run Table

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

l r Swap Array
0 4 h ↔ o o, e, l, l, h
1 3 e ↔ l o, l, l, e, h
2 2 stop o, l, l, e, h

The Solution Template

Swap the ends, walk inward.

Reverse String Code
1var reverseString = function(s) {
2 let l = 0, r = s.length - 1;
3 while (l < r) {
4 [s[l], s[r]] = [s[r], s[l]];
5 l++;
6 r--;
7 }
8};

Edge Cases & Common Mistakes

  • One character: l and r start equal; nothing to do.
  • Looping while l <= r: harmless, but swaps the middle character with itself.
  • Looping to n instead of n / 2: every pair is swapped twice and the array ends up unchanged.
  • Building a new string: uses O(n) memory; the problem asks for in place.

Summary

Reversing swaps each character with its mirror. Start l and r at the ends, swap, move both inward, and stop when they meet. O(n) time, O(1) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Point at both ends

    l = 0 and r = len(s) − 1.

  2. Swap and move inward

    While l < r, swap s[l] and s[r], then l++ and r--.

  3. Stop at the middle

    When l >= r, the array is reversed.

Frequently asked questions

Why not use the built-in reverse?

In a real codebase you should. In an interview, the point is to show the in-place two-pointer swap, which uses O(1) extra memory and is the building block for problems like Reverse Words and Rotate Array.


Why does the loop stop when l and r meet?

Each swap fixes two characters, one at each end. When the pointers meet, every pair has been swapped; for an odd length the middle character is already in place.


How do you reverse a string recursively?

Swap s[l] and s[r], then recurse on l + 1 and r − 1 until l >= r. It does the same swaps but uses O(n) stack space, so the loop is preferred.

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description