Goat Latin is a made-up word game. You get a sentence of words made of English letters, with exactly one space between neighbouring words.
Change every word like this. When its first letter is one of the five vowels, in upper or lower case, leave it alone; otherwise take its first letter off and put it on the end. Then add ma. Finally add a run of a letters whose length is the word's position in the sentence: one for the first word, two for the second, and so on. Return the new sentence.
Example 1
Input: sentence = "Eat green apples" Output: "Eatmaa reengmaaa applesmaaaa" Why: only green starts with a consonant
2 more examples and the constraints
Example 2
Input: sentence = "My cat" Output: "yMmaa atcmaaa" Why: both words move their first letter
Example 3
Input: sentence = "x" Output: "xmaa" Why: moving the only letter changes nothing
Constraints
- 1 ≤ sentence.length ≤ 150
- Only English letters and single spaces between words
- No space at the start or the end
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Convert each word on its ownO(n + w²)
- Grow the suffix as you goO(n + w²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 150-letter sentence | Verdict |
|---|---|---|---|
| Convert each word on its own | O(n + w²) | Passes; easy to read | |
| Grow the suffix as you go | O(n + w²) | Best; no index math |
n = length of the sentence, w = number of words.
Edge cases to test
- Capital vowels. "Ice" starts with a vowel even though I is a capital.
- One-letter words. Moving the first letter of "x" leaves "x".
- Keep the case. "My" becomes "yMmaa": the M moves but stays a capital.
- Many words. With 75 words the last one gets 75 a's; build them, do not count them by hand.
Common mistakes
- Checking only lowercase vowels, so "Eat" is treated as a consonant word.
- Starting the a-count at 0, so the first word gets no extra a.
- Lower-casing the whole word for the vowel check and returning that changed word.
How to talk through it
- 1Clarify. Do capital vowels count? Is there always one space between words?
- 2Restate the rules. Move a leading consonant, add "ma", add one a per position.
- 3Pick the loop. Split, handle each word, join. A running suffix avoids position math.
- 4Code it. Use a builder or a list so joining stays linear.
- 5Test out loud. Run "My cat" and "x" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?