← All Lessons Lesson 22 / 68
Lesson 22

Reverse the Vowels in a String

Reverse the Vowels in a String

In this lesson we solve a classic and very common interview problem. The idea is simple, but it teaches a powerful technique that you will use again and again.

The Problem

You are given a word (a string) called s. Your job is to reverse only the vowels in that word. Every other letter stays exactly where it is. You then return the changed word.

The vowels are the five letters: a, e, i, o, u. Both small and capital forms count, so A, E, I, O, U are vowels too. Every other letter is called a *consonant*, and consonants must never move.

Let's Understand With an Example

Take the word random.

  • The vowels inside it are a and o, in that order.
  • If we reverse just those vowels, a and o swap places. The a becomes o, and the o becomes a.
  • All the consonants r, n, d, m stay in their original spots.

So random turns into rondam. Notice the word still looks almost the same — only the two vowels traded seats.

A bigger example is afegijoku. Read out the vowels from left to right: a, e, i, o, u. Now reverse that list, so it becomes u, o, i, e, a. Put these reversed vowels back into the same vowel positions, one by one, and you get ufogijeka. The consonants f, g, j, k never moved.

The Key Idea: Two Pointers

The cleanest way to "reverse" something in place is the two-pointer trick. Picture two fingers:

  1. One finger starts at the left end of the word.
  2. The other finger starts at the right end.
  3. Move the left finger right until it lands on a vowel.
  4. Move the right finger left until it lands on a vowel.
  5. Now both fingers are on vowels — swap those two letters.
  6. Step both fingers inward and repeat.
  7. Stop when the two fingers meet or cross in the middle.

Why does this work? The first vowel should end up where the last vowel was, the second vowel where the second-last was, and so on. Swapping the outermost pair, then the next pair inward, does exactly that — it mirrors the vowels around the center without touching any consonant.

In Short

  • Walk from both ends toward the middle.
  • Skip every consonant; only stop on vowels.
  • When both sides point at a vowel, swap them and move on.
  • The rest of the string is left untouched.

This swap-and-move-inward pattern is the heart of many string and array problems, so learning it here will help you far beyond this single question.

Reverse the Vowels in a String
Diagram — click to zoom (scroll / drag to pan)