How to solve ‘reverseVowelsOfString’ in CodeFights

The question

Write a function that takes a string as input and returns the string with only the vowels reversed.
Note: The letters “a”, “e”, “i”, “o”, and “u” are vowels. The letter “y” is not a vowel.

Example

  • For s = "hello, world", the output should be
    reverseVowelsOfString(s) = "hollo, werld";
  • For s = "codefights", the output should be
    reverseVowelsOfString(s) = "cidefoghts";
  • For s = "eIaOyU", the output should be
    reverseVowelsOfString(s) = "UOaIye".

Input/Output

  • [time limit] 4000ms (py)
  • [input] string s

    Constraints:
    0 ≤ s.length ≤ 50.

  • [output] string

The Solution:

upup

 

The Explanation

We need to find out if a character is a vowel. An easy way to do it in python is to define a string and use

if … in …:

block. We add all the vowels in an array (stack logic). Then, reiterate over the input string and start creating an output string. Everytime we come across a vowel we use the one at the end of the array. If it is a consonant, we just copy that character to the output array.

This is obviously not the most efficient, or even a moderately efficient algorithm.

What we could do aside from this method is, instead of storing the letters, we could have stored the indices of the letters and everytime we came across a vowel, we could swap them with the one that it matches from the end. Let’s say we have 5 (or 6) vowels, we would swap first with last, second with last-1 and third with last-2). After swapping third one, we don’t swap anymore and just return the string. (Because we already swapped everything that has to be swapped)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s