Meta Data#
Difficulty: easy First Attempt: 2022-09-07
- Submissions: Accepted (first try)
Approach#
Translate each letter by the table, join into one string, and add it to a set; the answer is the set’s size (Hash Table). Letter c maps to table[ord(c) - ord("a")].
My Solution#
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
table = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--.."]
return len({"".join(table[ord(c) - ord("a")] for c in w) for w in words})
Complexity#
Time O(total characters), space O(total characters).
Mistakes to Avoid#
- Different words may share a Morse code; that is exactly what is being counted.
Interview Explanation#
I translate each word into its Morse string and return the number of distinct strings. Time is linear in the total length.
