← Home

804. Unique Morse Code Words

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
804

The trick here is to name the state correctly, then let the implementation follow. For 804. Unique Morse Code Words, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are uniqueMorseRepresentations.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(S), where S is the sum of the lengths of words in words. We iterate through each character of each word in words.
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
03
04For convenience, the full table for the 26 letters of the English alphabet is given below:
05
06[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
07Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.
08
09Return the number of different transformations among all words we have.
10
11Example:
12Input: words = ["gin", "zen", "gig", "msg"]
13Output: 2
14Explanation: 
15The transformation of each word is:
16"gin" -> "--...-."
17"zen" -> "--...-."
18"gig" -> "--...--."
19"msg" -> "--...--."
20
21There are 2 different transformations, "--...-." and "--...--.".
22Note:
23
24The length of words will be at most 100.
25Each words[i] will have length in range [1, 12].
26words[i] will only consist of lowercase letters.
27**/
28
29/**
30Approach #1: Hash Set [Accepted]
31Intuition and Algorithm
32
33We can transform each word into it's Morse Code representation.
34
35After, we put all transformations into a set seen, and return the size of the set.
36
37Java
38class Solution {
39    public int uniqueMorseRepresentations(String[] words) {
40        String[] MORSE = new String[]{".-","-...","-.-.","-..",".","..-.","--.",
41                         "....","..",".---","-.-",".-..","--","-.",
42                         "---",".--.","--.-",".-.","...","-","..-",
43                         "...-",".--","-..-","-.--","--.."};
44
45        Set<String> seen = new HashSet();
46        for (String word: words) {
47            StringBuilder code = new StringBuilder();
48            for (char c: word.toCharArray())
49                code.append(MORSE[c - 'a']);
50            seen.add(code.toString());
51        }
52
53        return seen.size();
54    }
55}
56
57Complexity Analysis
58
59Time Complexity: O(S), where S is the sum of the lengths of words in words. We iterate through each character of each word in words.
60
61Space Complexity: O(S).
62**/
63
64//Your runtime beats 85.31 % of cpp submissions.
65class Solution {
66public:
67    int uniqueMorseRepresentations(vector<string>& words) {
68        string morse[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
69        set<string> uniqueMorses;
70        for(int i = 0; i < words.size(); i++){
71            string s;
72            for(int j = 0; j < words[i].size(); j++){
73                s+=morse[(int)(words[i][j]-'a')];
74            }
75            uniqueMorses.insert(s);
76        }
77        return uniqueMorses.size();
78    }
79};

Cost

Complexity

Time
O(S), where S is the sum of the lengths of words in words. We iterate through each character of each word in words.
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.