Problem

You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:

  • If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word.
  • For example, the word "apple" becomes "applema".
    • If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add "ma".
  • For example, the word "goat" becomes "oatgma".
    • Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
  • For example, the first word gets "a" added to the end, the second word gets "aa" added to the end, and so on.

Return the final sentence representing the conversion from sentence to Goat Latin.

Examples

Example 1

1
2
Input: sentence = "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2

1
2
Input: sentence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Constraints

  • 1 <= sentence.length <= 150
  • sentence consists of English letters and spaces.
  • sentence has no leading or trailing spaces.
  • All the words in sentence are separated by a single space.

Solution

Method 1 – String Manipulation by Rules

Intuition

We process each word in the sentence according to the Goat Latin rules: check if it starts with a vowel or consonant, transform accordingly, and add the right number of ‘a’s based on its position.

Approach

  1. Split the sentence into words.
  2. For each word, check if it starts with a vowel (case-insensitive):
    • If yes, append “ma” to the word.
    • If no, move the first letter to the end, then append “ma”.
  3. Add ‘a’ repeated (word index + 1) times to the end of each word.
  4. Join all words with spaces and return the result.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    string toGoatLatin(string sentence) {
        stringstream ss(sentence);
        string word, ans;
        string vowels = "aeiouAEIOU";
        int idx = 1;
        while (ss >> word) {
            if (vowels.find(word[0]) != string::npos) {
                word += "ma";
            } else {
                word = word.substr(1) + word[0] + "ma";
            }
            word += string(idx, 'a');
            ans += word + " ";
            idx++;
        }
        ans.pop_back();
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func toGoatLatin(sentence string) string {
    words := strings.Fields(sentence)
    vowels := "aeiouAEIOU"
    for i, w := range words {
        if strings.ContainsRune(vowels, rune(w[0])) {
            words[i] = w + "ma"
        } else {
            words[i] = w[1:] + string(w[0]) + "ma"
        }
        words[i] += strings.Repeat("a", i+1)
    }
    return strings.Join(words, " ")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public String toGoatLatin(String sentence) {
        String[] words = sentence.split(" ");
        String vowels = "aeiouAEIOU";
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            String w = words[i];
            if (vowels.indexOf(w.charAt(0)) != -1) {
                w += "ma";
            } else {
                w = w.substring(1) + w.charAt(0) + "ma";
            }
            w += "a".repeat(i + 1);
            ans.append(w);
            if (i < words.length - 1) ans.append(' ');
        }
        return ans.toString();
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
    fun toGoatLatin(sentence: String): String {
        val vowels = "aeiouAEIOU"
        return sentence.split(" ").mapIndexed { i, w ->
            val s = if (w[0] in vowels) w + "ma" else w.drop(1) + w[0] + "ma"
            s + "a".repeat(i + 1)
        }.joinToString(" ")
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        vowels = set('aeiouAEIOU')
        words = sentence.split()
        ans = []
        for i, w in enumerate(words):
            if w[0] in vowels:
                nw = w + 'ma'
            else:
                nw = w[1:] + w[0] + 'ma'
            nw += 'a' * (i + 1)
            ans.append(nw)
        return ' '.join(ans)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
impl Solution {
    pub fn to_goat_latin(sentence: String) -> String {
        let vowels = "aeiouAEIOU";
        sentence.split_whitespace().enumerate().map(|(i, w)| {
            let mut s = if vowels.contains(w.chars().next().unwrap()) {
                format!("{}ma", w)
            } else {
                let mut chs = w.chars();
                let first = chs.next().unwrap();
                format!("{}{}ma", chs.collect::<String>(), first)
            };
            s.push_str(&"a".repeat(i + 1));
            s
        }).collect::<Vec<_>>().join(" ")
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    toGoatLatin(sentence: string): string {
        const vowels = new Set(['a','e','i','o','u','A','E','I','O','U']);
        return sentence.split(' ').map((w, i) => {
            let s = vowels.has(w[0]) ? w + 'ma' : w.slice(1) + w[0] + 'ma';
            s += 'a'.repeat(i + 1);
            return s;
        }).join(' ');
    }
}

Complexity

  • ⏰ Time complexity: O(n) — Each character is visited at most once.
  • 🧺 Space complexity: O(n) — Output string is proportional to input size.