https://leetcode.com/problems/goat-latin

This is easy prolem, where you need just to do what is asked, without really thinking.

  1. Split our sentence into words, using .split(). If it is not allowed we can just traverse it and find spaces.
  2. For every word check if it starts with vowel, if it is, add ma and i+1 letters a to the end. It is i+1, because we start from zero index.
  3. If first letter is not vowel, remove first letter and add it to the end, also add ma and letters a.

Complexity: time and space complexity is O(n) + O(k^2), where n is number of symbols in our string and k is number of words: do not forget about letters a in the end: we add 1 + 2 + ... + k = O(k^2) letters in the end.

class Solution:
    def toGoatLatin(self, S):
        words = S.split()
        vowels = set("AEIOUaeiou")
        for i in range(len(words)):
            if words[i][0] in vowels:
                words[i] = words[i] + "ma" + "a"*(i+1)
            else:
                words[i] = words[i][1:] + words[i][0] + "ma" + "a"*(i+1)
                
        return " ".join(words)

If you like the solution, you can upvote it on leetcode discussion section: Problem 0824