Python Solution [Approach #1: Head and Tail pointers [Accepted]]

  • 0

    Let's maintin head as an head pointer for string and tail as a tail pointer for string and define vowels chars vowels = 'aeiouAEIOU', then we apply next steps:

    • Iterate over string till head < tail
    • check if S[head] is in vowels chars and not so decrement tail pointer by one.
    • check if S[tail] is in vowels chars and S[head] not so increment head pointer by one.
    • check if now S[head] and S[tail] is a vowels chars so swap them:
      * S[head], S[tail] = S[tail], S[head]
    • then increment head by one and decrement tail by one.
    • return S


    class Solution:
        def reverseVowels(self, s):
            vowels = 'aeiouAEIOU'
            s = list(s)
            head, tail = 0, len(s) - 1
            while head < tail:
                if s[head] in vowels and s[tail] not in vowels:
                    tail -= 1
                if s[tail] in vowels and s[head] not in vowels:
                    head += 1
                if s[head] in vowels and s[tail] in vowels:
                    s[head], s[tail] = s[tail], s[head]
                head += 1
                tail -= 1
            return "".join(s)

    Complexity Analysis

    • Time Complexity: O(N), where N is the length of S.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.