We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Goat Latin

Number: 851

Difficulty: Easy

Paid? No

Companies: Meta


Problem Description

Given a sentence where words are separated by single spaces, convert the sentence to "Goat Latin". For each word, if it starts with a vowel (a, e, i, o, u in either case), append "ma". Otherwise, move the first letter to the end and then append "ma". Finally, append a number of letter 'a's at the end of each word equal to its position in the sentence (starting with 1).


Key Insights

  • Split the sentence into words.
  • For each word, check the first letter to decide if it starts with a vowel.
  • Modify each word according to the rules (vowel or consonant).
  • Append incremental 'a' characters based on the word's index.
  • Join the modified words back into a single string.

Space and Time Complexity

Time Complexity: O(n) where n is the total number of characters in the sentence. Space Complexity: O(n) for storing the resultant string and intermediate list of words.


Solution

We split the sentence into words and process each word one at a time. For each word:

  1. Check if the first letter (in lower case) is in the set {a, e, i, o, u}.
    • If yes, keep the word as is and append "ma".
    • Otherwise, remove the first letter, append it at the end, then append "ma".
  2. Append additional 'a' characters equal to the word's position in the sentence.
  3. After processing all words, join them with a space. This algorithm leverages basic string manipulation and iteration through the list of words. The key is to conditionally transform each word and then construct the final sentence in a single pass.

Code Solutions

# Function to convert sentence to Goat Latin
def toGoatLatin(sentence):
    # Define a set of vowels for quick lookup, including lowercase vowels
    vowels = set('aeiouAEIOU')
    # Split the sentence by spaces to get individual words
    words = sentence.split()
    # Initialize a list to hold the transformed words
    goat_latin_words = []
    
    # Iterate over each word with its index (starting from 0)
    for i, word in enumerate(words):
        # If the first letter is a vowel, keep the word as-is
        if word[0] in vowels:
            transformed = word + "ma"
        else:
            # If the word starts with a consonant, move the first letter to the end
            transformed = word[1:] + word[0] + "ma"
        # Append 'a' repeated (i+1) times
        transformed += "a" * (i + 1)
        # Add the transformed word to the list
        goat_latin_words.append(transformed)
        
    # Join the list back into a single string with spaces and return it
    return " ".join(goat_latin_words)

# Example usage
print(toGoatLatin("I speak Goat Latin"))
← Back to All Questions