Leetcode 824: Goat Latin

grid47
grid47
Exploring patterns and algorithms
Aug 16, 2024 6 min read

You are given a sentence with words separated by spaces. Each word consists of only lowercase and uppercase letters. Your task is to convert the sentence into a new language called ‘Goat Latin’ by following the rules below:

  1. If a word begins with a vowel (‘a’, ’e’, ‘i’, ‘o’, or ‘u’), append ‘ma’ to the end of the word.
  2. If a word begins with a consonant, remove the first letter, move it to the end, and add ‘ma’.
  3. Add one letter ‘a’ to the end of each word depending on its position in the sentence (1st word gets ‘a’, 2nd gets ‘aa’, 3rd gets ‘aaa’, etc.).

Return the final sentence in Goat Latin.

Problem
Approach
Steps
Complexity
Input: The input consists of a string, sentence, which contains words separated by spaces.
Example: Input: sentence = 'The quick brown fox'
Constraints:
• 1 <= sentence.length <= 150
• The sentence consists of English letters and spaces.
• There are no leading or trailing spaces in the sentence.
• All words are separated by a single space.
Output: The output is a string representing the sentence after converting it to Goat Latin.
Example: Output: 'heTmaa uickqmaaa rownbmaaaa oxfmaaaaa'
Constraints:
• The output must be a string.
Goal: The goal is to convert the sentence into Goat Latin according to the specified rules. Each word must be processed based on whether it starts with a vowel or consonant, and the appropriate suffix must be added based on the word's position in the sentence.
Steps:
• Step 1: Split the input sentence into words.
• Step 2: For each word, check if it starts with a vowel or consonant.
• Step 3: Modify the word accordingly (append 'ma' or move the first letter to the end and append 'ma').
• Step 4: Add the correct number of 'a's to the end of the word based on its position in the sentence.
• Step 5: Join all words back together into a final sentence.
Goal: Ensure that the input string satisfies the given constraints, particularly regarding the length of the sentence and the format of the words.
Steps:
• The sentence will not contain leading or trailing spaces.
• Each word in the sentence will be separated by exactly one space.
Assumptions:
• All words in the sentence are valid words made up of lowercase and uppercase English letters.
• There are no punctuation marks or special characters in the sentence.
Input: Input: sentence = 'The quick brown fox'
Explanation: The sentence 'The quick brown fox' would be converted to Goat Latin as 'heTmaa uickqmaaa rownbmaaaa oxfmaaaaa'. The first word starts with a consonant, so 'T' is moved to the end and 'ma' is added. The second word starts with a consonant, so 'q' is moved to the end, 'ma' is added, and one 'a' is appended. This continues for all words in the sentence.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus