← All coursesDSA Foundations

Lesson 7 of 19

Reversing with two pointers

Lay out a word on letter tiles. Point to the first and last tiles, trade their places, then move both pointers one place inward. Watch which tiles still need a turn.

One swap finishes both ends

In reverse order, the first tile belongs last and the last belongs first. After each swap, the tiles outside the two pointers are in their final positions. Swapping in a mutable array of n tiles takes O(n) time and O(1) extra space. Joining the result into a new string uses O(n) space for that string.

Work through an example

A sign has four loose tiles spelling POTS. What word do you get when you reverse them?

Step-by-step solution
  1. The two pointers start on P and S. Swap those tiles to get S O T P.
  2. Move both pointers inward. Swap O and T to get S T O P.
  3. The pointers cross. Every tile is in its final place, and the sign reads STOP.
JavaScript example
const tiles = ["P", "O", "T", "S"];
let left = 0;
let right = tiles.length - 1;
while (left < right) {
  const spare = tiles[left];
  tiles[left] = tiles[right];
  tiles[right] = spare;
  left++;
  right--;
}
tiles.join("");
DSA compiler

Try it yourself

Finish the animation to unlock this question.

When reversing five tiles, what should you do after the pointers meet at the middle tile?

Play Treasure Twins · Related exercise · String Reversal · See this stage of the beginner path