Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Luis Roel
Easier to understand than provided solution

Luis Roel

Aug 11, 2023

class Solution: def reverseVowels(self, s: str) -> str: # We need a way to do membership checks # and a set is a good way, since our reference # set isn't very large. vowels = set('aAeEiIoOuU') # Conver the string to a list so its easier to process s_list = [c for c in s] # Notice how the vowels switch sides? # hello -> holle, this tells me they're # processing the string from both ends # which means this is a good candidate for # two pointers l, r = 0, len(s) - 1 # Non inclusive because you can't flip the middle # onto itself while l < r: # The problem doesn't seem to mention we'll be dealing # with spaces...so I don't think there's a need to check # This line checks whether each index in the string contains # a vowel if s_list[l] in vowels and s_list[r] in vowels: # If it does, we just switch them s_list[l], s_list[r] = s_list[r], s_list[l] # And shift our pointers l += 1 r -= 1 # If we don't encounter vowels, keep shifting pointers # Remember, we want to make sure we don't miss any vowels # in the case that one pointer is pointing to a vowel and # another is not elif s_list[l] not in vowels: l += 1 elif s_list[r] not in vowels: r -= 1 # Turn our result back into a string. return ''.join(s_list)

0

0

Comments
Comments
Luis Roel
Luis Roel2 years ago

For defining s_list, for some reason doing list(s) didn't work as intended and makes a one element list from the string.