-
Notifications
You must be signed in to change notification settings - Fork 264
Reverse Vowels
Sar Champagne Bielert edited this page Apr 15, 2024
·
3 revisions
Unit 4 Session 1 (Click for link to problem statements)
Understand what the interviewer is asking for by identifying key aspects of the problem.
- Are we considering both uppercase and lowercase vowels?
- Yes, both cases should be considered.
- Does the order of consonants need to remain unchanged?
- Yes, only the vowels should be moved.
Plan the solution with pseudocode before coding.
General Idea: Use two pointers to locate vowels from both ends of the string and swap them until they meet.
1) Convert the string into a list to enable in-place swaps.
2) Set up two pointers, one starting at the beginning (`left`) and the other at the end (`right`) of the list.
3) While `left` pointer is less than `right` pointer:
a) Move `left` pointer rightward until it points to a vowel.
b) Move `right` pointer leftward until it points to a vowel.
c) If both pointers point to vowels, swap them and move both pointers towards the center.
4) Join the list back into a string and return.
- Skipping characters that are vowels due to incorrect condition checks.
- Not preserving the position of consonants.
def make_palindrome(s):
# Convert the string to a list to modify characters
chars = list(s)
left, right = 0, len(s) - 1
while left < right:
if chars[left] != chars[right]:
# Replace the character at the higher index with the smaller of the two
if chars[left] > chars[right]:
chars[left] = chars[right]
else:
chars[right] = chars[left]
left += 1
right -= 1
# Convert the list back to a string
return "".join(chars)