Unique Morse Code Words — LeetCode 804 Python Solution
- Problem
- #804
- Pattern
- Hash Map
- Reading time
- 6 min
- Source
- leetcode.com
The problem
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: 'a' maps to ".-", 'b' maps to "-...", 'c' maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.
Example
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Python solution
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
codes = [
".-",
"-...",
"-.-.",
"-..",
".",
"..-.",
"--.",
"....",
"..",
".---",
"-.-",
".-..",
"--",
"-.",
"---",
".--.",
"--.-",
".-.",
"...",
"-",
"..-",
"...-",
".--",
"-..-",
"-.--",
"--..",
]
s = {''.join([codes[ord(c) - ord('a')] for c in word]) for word in words}
return len(s)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 804. Unique Morse Code Words is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 804. Unique Morse Code Words?
- LeetCode 804. Unique Morse Code Words is rated Easy on LeetCode.
- What is the time complexity of LeetCode 804. Unique Morse Code Words?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 804. Unique Morse Code Words?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 804. Unique Morse Code Words cover?
- LeetCode 804. Unique Morse Code Words is tagged Array, Hash Table and String on LeetCode.