Similar Problems

Similar Problems not available

Unique Morse Code Words - Leetcode Solution


LeetCode:  Unique Morse Code Words Leetcode Solution

Difficulty: Easy

Topics: string hash-table array  

Problem Description:

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:


Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

Example 1:

Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".


  • The length of words will be at most 100.
  • Each words[i] will have length in range [1, 12].
  • words[i] will only consist of lowercase letters.


We can use a dictionary to store the Morse code representations of each letter. We can iterate through each word in words and for each character in the word, concatenate its Morse code representation to form the transformation of the word. We can then add this transformation to a set, which will automatically remove duplicate transformations. Finally, we can return the size of the set.

Here is the Python code implementation:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        morse_dict = { 'a': ".-", 'b': "-...", 'c': "-.-.", 'd': "-..", 'e': ".", 
                       'f': "..-.", 'g': "--.", 'h': "....", 'i': "..", 'j': ".---", 
                       'k': "-.-", 'l': ".-..", 'm': "--", 'n': "-.", 'o': "---", 
                       'p': ".--.", 'q': "--.-", 'r': ".-.", 's': "...", 't': "-", 
                       'u': "..-", 'v': "...-", 'w': ".--", 'x': "-..-", 'y': "-.--", 'z': "--.." }
        transformations = set()
        for word in words:
            transformation = ''
            for char in word:
                transformation += morse_dict[char]
        return len(transformations)

Time Complexity: O(n * m), where n is the number of words and m is the maximum length of a word.

Space Complexity: O(k), where k is the number of unique transformations. In the worst case where all words have unique transformations, k will be equal to n.

Unique Morse Code Words Solution Code