Goat Latin
Problem statement
You get a sentence of words separated by single spaces. Each word contains only English letters. Convert every word with these rules, then join the words back with single spaces:
- If the word starts with a vowel (
a,e,i,o,u, in either case), append"ma". - Otherwise, move its first letter to the end, then append
"ma". - Finally, append the letter
aonce for the first word, twice for the second word, and so on.
Return the converted sentence.
Examples
Example 1
Input: sentence = "Deploy the app"
Output: "eployDmaa hetmaaa appmaaaa"
Explanation: "Deploy" becomes "eployD" + "ma" + "a". "the" becomes "het" + "ma" + "aa". "app" starts with a vowel, so it becomes "app" + "ma" + "aaa".
Example 2
Input: sentence = "I ran"
Output: "Imaa anrmaaa"
Hints
Approach
Same rules, but build the output efficiently: collect converted words in a list (or a StringBuilder) and join once at the end, and grow the a suffix by one character per word instead of recreating it.
- Keep
suffix = ""and a listout. - For each word: add one
"a"tosuffix; convert the word; appendword + "ma" + suffixtoout. - Return
" ".join(out).
The output itself has length L = O(n + w²) for n input characters and w words (the a suffixes add 1 + 2 + … + w characters), so linear in the output is the best possible.
O(L)Space O(L)class Solution: def toGoatLatin(self, sentence: str) -> str: vowels = set("aeiouAEIOU") out = [] suffix = "" for word in sentence.split(" "): suffix += "a" # one more 'a' per word if word[0] in vowels: out.append(word + "ma" + suffix) else: out.append(word[1:] + word[0] + "ma" + suffix) return " ".join(out)Follow-up questions
- Keep punctuation attached to the end of a word in place, for example
"app,"becomes"appma,"plus the suffix. - Write the reverse function that turns Goat Latin back into the original sentence.
Frequently asked questions
The length of the output. It includes the growing a suffixes, which add up to w(w + 1)/2 characters for w words, so the output can be much longer than the input.
Repeated result = result + ... copies the whole string built so far each time. With a list and one join (or a StringBuilder), each character is written once.
It checks careful, rule-by-rule string handling with no clever algorithm to hide behind: the same care you need when rewriting log lines, renaming resources to a convention, or templating config values. Interviewers watch for the uppercase vowel case and for efficient string building.