Problem 804

Abstract / Summary

Given a list of words, count how many have unique translations to Morse code.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0804.py

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

        result = set()
        for w in words:
            m = ""
            for c in w:
                m += morse[ord(c) - ord("a")]
            result.add(m)
        return len(result)
11 lines | 462 bytes | submitted October 8, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method uniqueMorseRepresentations. The method receives a list of lowercase English words and returns the count of distinct Morse code strings that can be generated by translating each word. The algorithm proceeds by establishing a static mapping from letters to Morse symbols, iterating over each word to construct its Morse representation, storing each representation in a set to enforce uniqueness, and finally returning the size of that set.

Key Steps

Preparing the Morse alphabet

The method begins by declaring a list named morse that contains the 26 Morse code symbols in alphabetical order. This list serves as a direct lookup table where the index of each element corresponds to the position of the letter in the alphabet.

morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
         "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
         "..-","...-",".--","-..-","-.--","--.."]

Translating each word

A set called result is created to hold the unique Morse strings. The outer loop iterates over every word in the input list words. For each word, an empty string m is initialized. The inner loop walks through each character c of the current word, computes the zero-based alphabet index by subtracting the Unicode code point of 'a' from the code point of c, and appends the corresponding Morse symbol from the morse list to m.

result = set()
for w in words:
    m = ""
    for c in w:
        m += morse[ord(c) - ord("a")]
    result.add(m)

Recording unique representations

After the inner loop finishes constructing the full Morse string for a word, the string m is added to the result set. Because a set automatically discards duplicate entries, any repeated Morse representation produced by different words will be stored only once. Once all words have been processed, the method returns the number of distinct entries in the set.

return len(result)

Edge Cases Handled

When the input list words is empty, the outer loop never executes, leaving result as an empty set. The final len(result) call correctly yields 0, indicating that there are no Morse representations.

If a word in the list is an empty string, the inner loop does not iterate, leaving m as an empty string. The empty string is then added to the set, and it will be counted as a distinct representation if no other word also translates to an empty string. This behavior gracefully handles zero-length words without raising errors.

Repeated words, such as multiple occurrences of "gin" or "zen", generate identical Morse strings. Adding each of those strings to the set results in a single entry, ensuring that duplicates do not inflate the final count.

Words that consist of a single repeated character, for example "aaa" or "bbb", are processed correctly because the index calculation ord(c) - ord("a") yields the same value for each occurrence, and the corresponding Morse symbol is concatenated the appropriate number of times.

All letters are assumed to be lowercase English alphabet characters. The direct subtraction from ord("a") guarantees a valid index in the range 0 to 25. Consequently, any input that respects this contract is handled without additional checks.

Performance Optimizations Observed

The algorithm uses a pre-computed list of Morse symbols, allowing constant-time retrieval of a symbol given a character’s alphabet index. The index calculation ord(c) - ord("a") is a simple arithmetic operation that avoids more expensive dictionary lookups.

Storing the results in a Python set provides average-case constant-time insertion and membership testing, which efficiently eliminates duplicate Morse strings as they are generated.

String concatenation inside the inner loop builds the Morse representation incrementally. While Python strings are immutable, the concatenation pattern used here benefits from the interpreter’s internal optimizations for short strings, keeping the overhead modest for typical word lengths.

Overall, the method processes each character exactly once, leverages direct indexing for symbol lookup, and relies on the built-in set data structure to manage uniqueness with minimal overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a library of special symbols that turn letters into short beeps and long buzzes. The sequence of letters starts with a list that holds all those secret codes for a through z. To figure out how many different signals exist, the computer looks at each word in a pile. It takes every single letter in a word and swaps it for its matching beep and buzz code from the library. Once all the letters are swapped, they are glued together into one long signal for that word. To keep track of the unique signals, the computer drops each finished signal into a bucket. If a signal is already in the bucket, it just stays there. After checking every word, the bucket holds only the ones that are different from each other.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.81 | σ = 0.72

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
fengvyi C++
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
fengvyi C++
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
38 links | 24 authors | 10 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 1 medium
4 solutions   October 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality