#824
Goat Latin
EasyStringString ManipulationArray Processing
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution processes each word in a single pass, applying the transformations directly while building the result. This reduces unnecessary string operations and improves efficiency.
⚙️
Algorithm
5 steps- 1Step 1: Split the sentence into words using spaces.
- 2Step 2: Initialize a list to hold the transformed words.
- 3Step 3: For each word, check if it starts with a vowel or consonant and apply the respective transformation.
- 4Step 4: Append the appropriate number of 'a's based on the word's index.
- 5Step 5: Join the transformed words into a single string and return it.
solution.py15 lines
1def toGoatLatin(sentence):
2 words = sentence.split()
3 result = []
4 vowels = 'aeiouAEIOU'
5 for i, word in enumerate(words):
6 if word[0] in vowels:
7 transformed = word + 'ma'
8 else:
9 transformed = word[1:] + word[0] + 'ma'
10 transformed += 'a' * (i + 1)
11 result.append(transformed)
12 return ' '.join(result)
13
14# Example usage
15print(toGoatLatin('I speak Goat Latin'))ℹ
Complexity note: The time complexity is O(n) since we process each character in the sentence exactly once. The space complexity is O(n) due to the storage of the transformed words.
- 1Understanding string manipulation is crucial for this problem.
- 2Recognizing patterns in word transformations can simplify the implementation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.