Unique Morse Code Words - Problem

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes. For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...".

Return the number of different transformations among all words we have.

Input & Output

Example 1 — Basic Case
$ Input: words = ["gin", "zen", "gig"]
Output: 2
💡 Note: gin → '--..-..' (g='--.', i='..', n='-.'). zen → '--..-..' (z='--..', e='.', n='-.'). gig → '----..--.' (g='--.', i='..', g='--.'). We have gin and zen with the same morse transformation '--..-..' and gig with a different one. So we have 2 unique transformations.
Example 2 — All Different
$ Input: words = ["a", "b", "c"]
Output: 3
💡 Note: a → '.-', b → '-...', c → '-.-.'. All three morse codes are different, so 3 unique transformations.
Example 3 — All Same
$ Input: words = ["cab", "bac", "abc"]
Output: 1
💡 Note: cab → '-.-..--...', bac → '-...-.-..-', abc → '.--...-.-.' All three words produce different morse transformations when the order matters, so we have 3 unique transformations, not 1.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 12
  • words[i] consists of lowercase English letters only

Visualization

Tap to expand
Unique Morse Code Words INPUT words[] array: "gin" "zen" "gig" Morse Code Map: g = --. i = .. n = -. z = --.. e = . Each letter maps to dots and dashes ALGORITHM STEPS 1 Create HashSet Store unique transformations 2 Transform each word Convert letters to Morse "gin" --> --...-. "zen" --> --...-. "gig" --> --...--. "gin" and "zen" are same! 3 Add to HashSet Duplicates auto-filtered 4 Return set size Count unique codes FINAL RESULT HashSet Contents: "--...-." [1] "--...--." [2] Only 2 unique codes! Output: 2 OK - 2 different transformations found Key Insight: HashSet automatically handles duplicates - when "gin" and "zen" produce the same Morse code, only one entry is stored. The set's size gives us the count of unique transformations. Time: O(n*m) where n=words, m=avg length | Space: O(n) for HashSet storage TutorialsPoint - Unique Morse Code Words | Hash Set Optimization
Asked in
Google 15 Amazon 12 Facebook 8
125.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen