In Morse code every lower-case letter has its own pattern of dots and dashes: a is .-, b is -..., c is -.-., and so on through z, which is --... The full table of 26 patterns is fixed and given to you.
To encode a word, write the pattern of each of its letters one after another with no gaps. Because there are no gaps, different words can end up with the very same code. Given a list words, return how many different codes the words produce.
Example 1
Input: words = ["a", "et", "n", "te", "s"] Output: 3 Why: a and et both give .-, n and te both give -., s gives ...
2 more examples and the constraints
Example 2
Input: words = ["eee", "s", "ie", "ei"] Output: 1 Why: all four words encode to ...
Example 3
Input: words = ["ok"] Output: 1 Why: one word, one code
Constraints
- 1 ≤ number of words ≤ 100
- 1 ≤ length of each word ≤ 12
- Words contain only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- List of distinct codesO(n²·L)
- Hash set of codesO(S)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 words of 12 letters | Verdict |
|---|---|---|---|
| List of distinct codes | O(n²·L) | Works; extra scans | |
| Hash set of codes | O(S) | Best; one lookup per word |
n = number of words, L = longest word, S = total letters in all words.
Edge cases to test
- One word. The answer is 1.
- Every word encodes the same. "eee", "s", "ie" and "ei" all give
...: answer 1. - Repeated words. The same word twice adds one code, not two.
- Different lengths, same code. "a" has one letter and "et" has two, yet both give
.-.
Common mistakes
- Counting distinct words instead of distinct codes.
- Putting a space or separator between letter patterns, which hides the collisions the question is about.
- Indexing the table with the character itself instead of its offset from
a.
How to talk through it
- 1Clarify. Are letters joined with no gap? Do we count codes or words? Only lower-case letters?
- 2Describe the encoding. Each word becomes one string: its letters' patterns glued together.
- 3Pick the structure. Counting different values is what a set does; a list would need a scan per word.
- 4Code it. Build the code with a string builder, add it to the set, return the size.
- 5Test out loud. Run "a" and "et": they must count as one code.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?