We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Unique Morse Code Words

Number: 822

Difficulty: Easy

Paid? No

Companies: Wix


Problem Description

Given an array of words, each word is transformed into a Morse code string by converting each character to its Morse representation and concatenating them. The task is to count how many unique Morse code transformations exist among the input words.


Key Insights

  • Use a pre-defined mapping of each letter ('a' to 'z') to its Morse code representation.
  • For every word, build its Morse code transformation by concatenating the Morse strings of each character.
  • Store each transformation in a set to automatically handle duplicates.
  • The number of unique transformations is the size of the set at the end.

Space and Time Complexity

Time Complexity: O(n * m) where n is the number of words and m is the average length of a word. Space Complexity: O(n * k) where k is the average length of the Morse transformation (which depends on m) to store all unique transformations.


Solution

The algorithm processes each word by iterating over each character, retrieving its Morse code, and concatenating these codes to form a transformation string. A set is used to collect the transformations ensuring that duplicates are automatically removed. Finally, the count of unique transformations is returned. Key data structures used are an array/list for the input words, a mapping for letters to Morse code, and a set for tracking unique transformations.


Code Solutions

# Define the mapping from each letter to its Morse code representation.
morse_codes = [
    ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", 
    "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", 
    "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", 
    "-.--", "--.."
]

def unique_morse_representations(words):
    # A set to keep track of the unique Morse code transformations
    unique_transformations = set()
    
    # Iterate over each word in the list
    for word in words:
        # Build the Morse transformation for the current word
        transformation = ''
        for char in word:
            # Convert character to its corresponding Morse code using its index
            transformation += morse_codes[ord(char) - ord('a')]
        # Add the transformation to the set
        unique_transformations.add(transformation)
        
    # Return the number of unique transformations
    return len(unique_transformations)

# Example usage:
words = ["gin", "zen", "gig", "msg"]
print(unique_morse_representations(words))  # Output should be 2
← Back to All Questions