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.
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.
Take the word random.
a and o, in that order.a and o swap places. The a becomes o, and the o becomes a.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 cleanest way to "reverse" something in place is the two-pointer trick. Picture two fingers:
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.
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.