↓Skip to main content
  1. LeetCode/

LeetCode 824: Goat Latin

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-15

  • Submissions: Accepted ×2

Approach
#

Split into words and convert each (String Template 6): leave a word starting with a vowel (either case) unchanged, otherwise move its first letter to the end; then append "ma" and i + 1 copies of "a" (with i the 0-based word index).

My Solution
#

class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        res = []
        for i, w in enumerate(sentence.split()):
            if w[0] not in "aeiouAEIOU":
                w = w[1:] + w[0]
            res.append(w + "ma" + "a" * (i + 1))
        return " ".join(res)

Complexity
#

Time O(n + w²) for w words, since the appended as total O(w²); space likewise.

Mistakes to Avoid
#

  • Vowels include uppercase.
  • The first word gets one a, not zero.

Interview Explanation
#

I split the sentence, move a leading consonant to the end, append ma plus index + 1 copies of a, and join with spaces.

Related

LeetCode 804: Unique Morse Code Words
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 804 note: translate each word into a Morse string and count the distinct results with a set
LeetCode 657: Robot Return to Origin
·1 min
LeetCode Easy String Simulation
LeetCode 657 note: returning to the origin means as many U as D and as many L as R
LeetCode 557: Reverse Words in a String III
·1 min
LeetCode Easy Two-Pointers String
LeetCode 557 note: split on spaces, reverse each word, and join with spaces
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 520: Detect Capital
·1 min
LeetCode Easy String
LeetCode 520 note: only three forms are valid: all caps, all lowercase, or only the first letter capitalized
LeetCode 521: Longest Uncommon Subsequence I
·1 min
LeetCode Easy String
LeetCode 521 note: identical strings give -1; otherwise the longer string itself is the answer