File: unique-morse-code-words/solution.py

Date: 2026-06-06

Time: 19:36

unique-morse-code-words/solution.py

Purpose

This file is a self-contained solution to LeetCode 804 — Unique Morse Code Words. It owns both the solution logic and its test suite in a single module. The problem: given a list of lowercase English words, translate each to Morse code by concatenating per-letter codes, then count how many distinct Morse strings result.

Key Components

Solution.uniqueMorseCodeWords(words: List[str]) -> int — The only public method. Takes a list of lowercase words, returns the count of unique Morse representations.

morse (local list, 26 elements) — A lookup table mapping index 0–25 to the Morse code for 'a''z'. This is the canonical ITU Morse alphabet. The table is defined inline rather than as a class or module constant, which keeps it scoped to the method.

TestSolution — Five test cases covering the LeetCode examples, deduplication, single-character words, and the critical property that different words can collide to the same Morse string ("gig" and "msg" both map to "--...---.").

Patterns

Set-comprehension for deduplication — The core logic is a single expression: build a set of Morse strings via { "".join(...) for word in words }, then take len(). This is the standard Python idiom for "count distinct values of a transformation."

ord(c) - ord("a") indexing — Converts a lowercase letter to its 0-based index without importing anything. This works because the problem guarantees lowercase English letters only.

Solution + tests in one file — Matches the project convention visible across the repo tree. Each problem directory has a solution.py that bundles implementation and unittest tests, runnable via python -m unittest or if _name == "main_".

Dependencies

Imports: typing.List (type annotation) and unittest (test harness). No external packages.

Imported by: The test_solution.py in this same directory imports from it. The massive "Imported By" list in the prompt is misleading — those are test files from *other* problems that share the same structural pattern, not actual import dependencies on this file.

Flow

1. Define the 26-element Morse lookup table.

2. For each word in the input, map each character c to morse[ord(c) - ord('a')] and join into one string.

3. Collect all such strings into a set (deduplication happens here).

4. Return the set's cardinality.

The entire computation is O(S) where S is the total number of characters across all words — each character is visited exactly once for the join, and set insertion is amortized O(1).

Invariants

Error Handling

None. The code assumes valid input per LeetCode constraints. An out-of-range character would raise an IndexError from the list access. There's no explicit validation or exception handling — appropriate for a competitive-programming-style solution where input is guaranteed well-formed.