
Sponsored
Sponsored
We can utilize a HashSet data structure to store the unique transformations. For each word, we can generate its Morse code transformation by replacing each character by its corresponding Morse code. We then add each transformation to the HashSet to automatically handle duplicates. The size of the HashSet at the end gives us the number of unique transformations.
Time Complexity: O(N), where N is the total number of characters across all words.
Space Complexity: O(WL), where W is the number of words and L is the length of the longest word, due to storing transformations.
1def uniqueMorseRepresentations(words):
2 morse_map = [
3 ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
4 ]
5 unique_transformations = set()
6 for word in words:
7 transformation = ''.join(morse_map[ord(c) - ord('a')] for c in word)
8 unique_transformations.add(transformation)
9 return len(unique_transformations)
10
11words = ["gin", "zen", "gig", "msg"]
12print(uniqueMorseRepresentations(words))In the Python version, we use a set to track unique Morse code transformations. As each word is processed, its corresponding Morse code is generated using list comprehension and joined into a string which is then added to the set. In the end, the size of the set indicates the count of unique transformations.
In this method, we establish a direct mapping of characters to Morse code using a fixed array index, which simplifies the translation process by utilizing the ASCII value difference between 'a' and the current character. We then use the translated words to populate a set directly, ensuring uniqueness of each transformation.
Time Complexity: O(N^2), due to checking each transformation against existing ones in the list.
Space Complexity: O(WL), where W is the word count and L is the length of the longest word, needed to store transformations.
This concise JavaScript implementation congregates Morse letters, directly utilizing a JavaScript Set to distinguish unique Morse transformations without redundancy.