Unique morse code words

August 17, 2022

array-and-hashmap

Problem URL: Unique morse code words

We will translate each word to a morse code and then add that to a set. Finally return the number of elements of that set.

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        res = set()
        for word in words:
            code = ''
            for c in word:
                code += morse[ord(c)-ord('a')]
            res.add(code)
        return len(res)

Time Complexity: O(n*m), n is the number of words, m is length of largest word.
Space Complexity: O(n)