Goat Latin
Problem
Convert a sentence to Goat Latin. If a word begins with a vowel, append "ma". Otherwise move the first letter to the end and add "ma". Then append "a" repeated by the 1-based word index.
sentence = "I speak Goat Latin""Imaa peaksmaaa oatGmaaaa atinLmaaaaa"def toGoatLatin(sentence):
vowels = set("aeiouAEIOU")
out = []
for i, w in enumerate(sentence.split(), 1):
if w[0] in vowels:
out.append(w + "ma" + "a" * i)
else:
out.append(w[1:] + w[0] + "ma" + "a" * i)
return " ".join(out)
function toGoatLatin(sentence) {
const vowels = new Set("aeiouAEIOU");
const words = sentence.split(" ");
return words.map((w, idx) => {
const i = idx + 1;
const base = vowels.has(w[0]) ? w : w.slice(1) + w[0];
return base + "ma" + "a".repeat(i);
}).join(" ");
}
class Solution {
public String toGoatLatin(String sentence) {
String vowels = "aeiouAEIOU";
String[] words = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String w = words[i];
String base = vowels.indexOf(w.charAt(0)) >= 0 ? w : w.substring(1) + w.charAt(0);
sb.append(base).append("ma");
for (int j = 0; j <= i; j++) sb.append('a');
if (i < words.length - 1) sb.append(' ');
}
return sb.toString();
}
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string toGoatLatin(string sentence) {
string vowels = "aeiouAEIOU";
stringstream ss(sentence), out;
string w;
int i = 1;
while (ss >> w) {
if (vowels.find(w[0]) == string::npos) w = w.substr(1) + w[0];
w += "ma" + string(i, 'a');
if (i > 1) out << ' ';
out << w;
i++;
}
return out.str();
}
};
Explanation
Goat Latin just applies a fixed recipe to each word of the sentence, so we split on spaces and transform the words one by one, then join them back together.
For each word we check its first letter. If it is a vowel, we keep the word as is; if it is a consonant, we move that first letter to the end (w[1:] + w[0]). Then we glue on "ma" followed by the letter 'a' repeated by the word's 1-based position ("a" * i).
Using enumerate(..., 1) hands us that position i directly, so word 1 gets one a, word 2 gets two, and so on.
Example: "I speak Goat Latin". Word 1 "I" starts with a vowel → "I" + "ma" + "a" = "Imaa". Word 2 "speak" is a consonant → "peak" + "s" + "ma" + "aa" = "peaksmaaa", and the pattern continues.
Each word is handled with a small amount of work proportional to its length, so the whole sentence is processed in linear time.