#804
Unique Morse Code Words
EasyArrayHash TableStringHash MapArray
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 approach uses a set to store unique Morse code transformations directly, eliminating the need for nested loops. This reduces time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Create a Morse code mapping for each letter.
- 2Step 2: Initialize a set to store unique Morse transformations.
- 3Step 3: For each word, convert it to Morse code and add the transformation to the set.
- 4Step 4: Return the size of the set, which represents the number of unique transformations.
solution.py7 lines
1def uniqueMorseRepresentations(words):
2 morse_code = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
3 transformations = set()
4 for word in words:
5 transformation = ''.join(morse_code[ord(c) - ord('a')] for c in word)
6 transformations.add(transformation)
7 return len(transformations)ℹ
Complexity note: The time complexity is O(n) because we only iterate through the list of words once, and each transformation is computed in constant time. The space complexity is O(n) due to the storage of unique transformations in a set.
- 1Using a set allows for efficient tracking of unique transformations.
- 2Understanding Morse code mapping is crucial for the transformation process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.