InterviewPrepKit

Home / Coding / Two Pointers

Reverse Vowels of a String

easy Original β†—
Solving tips
  • It's in-place array reversal with a filter: converge two pointers from the ends, but each first skips non-vowels, then swap when both rest on vowels.
  • Skipping consonants preserves their positions for free; only vowel-vowel pairs swap, performing exactly the required permutation.
  • Test membership against a set of both cases 'aeiouAEIOU'; keep the original character casing in the output.
  • Strings are immutable in Python, so work on list(s) and ''.join; O(n) time, and re-check left < right each step so pointers never cross and double-swap.

Problem

Given a string s, reverse the order of only its vowels and return the result. Every consonant (and any other character) stays exactly where it is; the vowels swap positions among themselves so that the first vowel trades places with the last, the second with the second-to-last, and so on.

Vowels are a, e, i, o, u in both lowercase and uppercase. The string may contain letters and printable ASCII characters.

Examples

  • s = "hello" β†’ "holle" Vowels are e (index 1) and o (index 4); they swap, consonants h,l,l stay put.
  • s = "leetcode" β†’ "leotcede" Vowel sequence e,e,o,e reverses to e,o,e,e in the same four slots.
  • s = "aA" β†’ "Aa" Case matters for identity but not for membership: both characters are vowels and they swap.

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of printable ASCII characters.
  • Expected O(n) time β€” with 3 * 10^5 characters, anything quadratic is too slow.

Think about it first

Hint 1 Only the vowels move, and they land exactly in the slots vowels already occupy β€” the set of vowel *positions* is unchanged, only which vowel sits where.
Hint 2 Think of how you'd reverse a whole array with two pointers converging from the ends. What should a pointer do when it's sitting on a consonant?
Hint 3 Walk `left` rightward until it hits a vowel and `right` leftward until it hits a vowel; swap them, step both inward, repeat until the pointers cross. Strings are immutable in Python, so do it on `list(s)` and join at the end.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.