851. Goat Latin
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to convert a given English sentence into a fictional language called "Goat Latin" by applying a specific set of rules to each word. The transformation rules depend on two factors: whether a word starts with a vowel or a consonant, and the word's position (index) in the sentence.
Solution
Goat Latin in Python
class Solution:
def toGoatLatin(self, sentence: str) -> str:
# Create a set of vowels for efficient O(1) lookup.
vowels = set('aeiouAEIOU')
# Split the sentence into a list of words.
words = sentence.split(' ')
# List to hold the transformed words.
result_words = []
# Enumerate through words to get both index and value.
for i, word in enumerate(words):
# Rule 1: If the word begins with a vowel, append "ma".
if word[0] in vowels:
new_word = word + 'ma'
# Rule 2: If the word begins with a consonant, move the first letter
# to the end and then append "ma".
else:
new_word = word[1:] + word[0] + 'ma'
# Rule 3: Add 'a's based on the 1-based word index.
# (i + 1) because enumerate gives a 0-based index.
new_word += 'a' * (i + 1)
result_words.append(new_word)
# Join the transformed words back into a single sentence with spaces.
return ' '.join(result_words)
Goat Latin in Java
class Solution {
public String toGoatLatin(String sentence) {
// Set of vowels for O(1) lookup, handling both uppercase and lowercase.
Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
// Split the sentence into words.
String[] words = sentence.split(" ");
// Use StringBuilder for efficient string construction.
StringBuilder result = new StringBuilder();
// Suffix of 'a's to be appended, grows with each word.
StringBuilder suffixA = new StringBuilder("a");
for (int i = 0; i < words.length; i++) {
String word = words[i];
char firstChar = word.charAt(0);
// Apply Goat Latin rules to the word.
if (vowels.contains(firstChar)) {
// Rule 1: Word begins with a vowel.
result.append(word);
result.append("ma");
} else {
// Rule 2: Word begins with a consonant.
result.append(word.substring(1));
result.append(firstChar);
result.append("ma");
}
// Rule 3: Add 'a's based on the word's 1-based index.
result.append(suffixA);
suffixA.append('a'); // Prepare for the next word.
// Add a space if it's not the last word.
if (i < words.length - 1) {
result.append(" ");
}
}
return result.toString();
}
}
Goat Latin in C++
class Solution {
public:
string toGoatLatin(string sentence) {
// Set of vowels for quick lookup (both cases).
unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
// Use a stringstream to easily split the sentence by spaces.
stringstream ss(sentence);
string word;
string result = "";
string suffix_a = "a"; // This will be appended and grown in each iteration.
bool first_word = true;
// Process each word from the stringstream.
while (ss >> word) {
// Add a space before each word except the first one.
if (!first_word) {
result += " ";
}
first_word = false;
char first_char = word[0];
// Check if the word starts with a vowel.
if (vowels.count(first_char)) {
// Rule 1: Starts with a vowel.
result += word + "ma";
} else {
// Rule 2: Starts with a consonant.
result += word.substr(1) + first_char + "ma";
}
// Rule 3: Add 'a's based on word index.
result += suffix_a;
suffix_a += 'a'; // Prepare suffix for the next word.
}
return result;
}
};
Goat Latin in TypeScript
function toGoatLatin(sentence: string): string {
// Set of vowels for O(1) lookup, handling both cases.
const vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
// Split the sentence into an array of words.
const words = sentence.split(' ');
// Array to hold the transformed words.
const resultWords: string[] = [];
// Iterate through the words with their index.
for (let i = 0; i < words.length; i++) {
const word = words[i];
let newWord = '';
// Rule 1: If the word begins with a vowel, append "ma".
if (vowels.has(word[0])) {
newWord = word + 'ma';
} else {
// Rule 2: If the word begins with a consonant, move the first letter
// to the end, then append "ma".
newWord = word.slice(1) + word[0] + 'ma';
}
// Rule 3: Add 'a's based on the 1-based word index.
// 'a'.repeat is an efficient way to create a string of repeated characters.
newWord += 'a'.repeat(i + 1);
resultWords.push(newWord);
}
// Join the transformed words back into a sentence with spaces.
return resultWords.join(' ');
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.