Morse Code Translator
  1. Translator
  2. Unique Morse code words

Unique Morse code words (LeetCode 804)

In LeetCode 804 you write each word as the Morse code of its letters with no gaps, then count the different results. Put each result in a set and return the set's size.

In short: turn every word into the Morse code of its letters written one after another, put each result in a set, and return the size of the set. A set keeps one copy of each value, so its size is the number of different transformations. It takes one pass over the letters.

What does LeetCode 804 ask?

You get a list of lowercase words. Each letter has a code from the international Morse alphabet, and you write a word by placing its letters' codes side by side with nothing between them. The exercise calls the result the word's transformation. Your job is to return how many different transformations the list produces (LeetCode Wiki). The task is problem 804 on LeetCode (LeetCode Wiki), where you can submit your own solution: Unique Morse Code Words on LeetCode.

The task needs no decoding and no timing. You only need the 26 letter codes, and they are the standard ones: this site's table of letters, the Morse code alphabet, matches them (ITU-R M.1677-1). The wiki gives the limits as at most 100 words of at most 12 letters each (LeetCode Wiki), so a long input is not the difficulty. Counting the right thing is.

Why do different words share a transformation?

A transformation has no gaps. In real Morse code the pause between letters is what tells the listener where one letter ends: it lasts three times as long as a dot, while the pause inside a letter lasts one (ITU-R M.1677-1). Drop those pauses and the boundaries vanish, so different letter sequences can produce the same string of dots and dashes. The table below has three pairs that collide, built from this site's table; each pair is one transformation, so a list holding both words counts it once.

Two differently arranged ribbons merge into one overlapping ribbon in a shallow bowl.
Illustration: Different paths to one transformation
Pairs of different words with the same transformation, built from this site's Morse table
WordCode of each letterTransformation
ago
jam
et
a
ee
i

Listen to the first pair. The signals are the same, but the pauses are not, which is the only reason you can tell them apart:

AGO: three letters, separated by pauses.
JAM: the same signals as AGO, grouped differently.

The same ambiguity is why a message without its pauses is hard to read. Decoding Morse code without spaces looks at that problem from the other side.

How do you solve it?

Three steps, none of them clever:

  1. Write a function that turns one word into its transformation: look up each letter's code and join them with no separator.
  2. Apply it to every word and keep the results in a set. A set is an unordered collection with no duplicate elements (Python Tutorial, Sets), so adding a transformation that is already there changes nothing.
  3. Return the length of the set.

You do not compare words with each other, and you never have to decide which words collide. The set does that on its own.

A Python solution that was run

The code below uses a set comprehension, which Python supports like a list comprehension (Python Tutorial, Sets). Letters are looked up by their position: ord(letter) - ord("a") is 0 for a and 25 for z. Save it as solution.py. The table was generated from this site's own Morse table, not typed by hand.

For LeetCode, submit MORSE, both helper functions and the Solution class. Omit the __main__ demonstration block. Keep that block when running the standalone version.

MORSE = [
    ".-", "-...", "-.-.", "-..", ".", "..-.",
    "--.", "....", "..", ".---", "-.-", ".-..",
    "--", "-.", "---", ".--.", "--.-", ".-.",
    "...", "-", "..-", "...-", ".--", "-..-",
    "-.--", "--..",
]
assert len(MORSE) == 26


def transformation(word):
    """The code of each letter, written one after another with no gaps."""
    return "".join(MORSE[ord(letter) - ord("a")] for letter in word)


def unique_transformations(words):
    return len({transformation(word) for word in words})


class Solution:
    def uniqueMorseRepresentations(self, words):
        return unique_transformations(words)


if __name__ == "__main__":
    for word in ["ago", "jam", "et", "a", "ee", "i"]:
        print(word, transformation(word))

    checks = [
        (["ago", "jam", "aim", "rat"], 2),
        (["ago", "jam"], 1),
        (["et", "a", "ee", "i"], 2),
        (["sos"], 1),
        (["e", "t", "e"], 2),
    ]
    for words, expected in checks:
        got = unique_transformations(words)
        print(words, "->", got, "ok" if got == expected else f"expected {expected}")

    spaced = {" ".join(MORSE[ord(c) - ord("a")] for c in word) for word in ["ago", "jam"]}
    print(len(spaced), "different results when a space separates the letters")

The output of python3 solution.py, from a real run:

ago .---.---
jam .---.---
et .-
a .-
ee ..
i ..
['ago', 'jam', 'aim', 'rat'] -> 2 ok
['ago', 'jam'] -> 1 ok
['et', 'a', 'ee', 'i'] -> 2 ok
['sos'] -> 1 ok
['e', 't', 'e'] -> 2 ok
2 different results when a space separates the letters

The first block of lines prints the transformations from the table above. The checks then run five small lists. In the third, et and a collide, and so do ee and i, which leaves two different transformations. The last line shows the usual mistake: join the letters with a space and ago and jam no longer collide, so you count 2 instead of 1. The exercise wants no separator.

How fast is it?

Call the total number of letters across all words L. Each letter costs one table lookup and one append, so building all the transformations takes time proportional to L. Adding to a set and testing membership are O(1) operations on average in Python's own table, which assumes that hashing a key takes constant time (Python documentation, time complexity). Your keys are strings, and hashing a string reads all of it, so count that work as proportional to the string's length: the total stays proportional to L. Memory is proportional to L too, because in the worst case every transformation is different and the set holds them all.

With the limits above, the longest possible input is 100 words of 12 letters, or 1200 letters. No letter's code has more than 4 signals, so no transformation is longer than 48 signals (computed from this site's table). That is tiny, and a plain set is all you need.

Do real words collide often?

Yes. This script reads the word list at /usr/share/dict/words, the word list that ships with macOS (a large list that includes rare words), keeps the lowercase ASCII words and counts their transformations. Save it next to solution.py, and change the path if your system keeps the list elsewhere:

from solution import transformation

with open("/usr/share/dict/words") as file:
    words = [line.strip() for line in file]
words = [word for word in words if word.isascii() and word.isalpha() and word.islower()]

print(len(words), "lowercase words")
print(len({transformation(word) for word in words}), "different transformations")

The output of a run on a Mac:

210773 lowercase words
197322 different transformations

That is 13,451 fewer transformations than words. Your list will give other numbers. The point is that the count is smaller than the number of words, which is what the exercise measures.

Where to go from here

If you wrote your own table by hand, compare it letter by letter with the alphabet and check any word in the translator. Morse code in Python builds the same dictionary and goes on to decoding and timing. The Arduino and Raspberry Pi guides, Morse code with Arduino and Morse code with Raspberry Pi, send those codes to real hardware. To hear the pauses the exercise ignores, start with Morse code timing or learn Morse by ear.

Sources

  1. 804. Unique Morse Code Words, LeetCode Wiki. doocs/leetcode (open-source LeetCode solutions), checked 11 November 2026.
  2. Data Structures, Sets, The Python Tutorial. Python Software Foundation, checked 11 November 2026.
  3. Time complexity of operations on built-in types. Python Software Foundation, checked 11 November 2026.
  4. Recommendation ITU-R M.1677-1, International Morse code. ITU Radiocommunication Sector, October 2009.