Unique Morse Code Words
Problem
Given a list of words, each letter is translated using a fixed Morse alphabet. The transformation of a word is the concatenation of its letters' Morse codes. Return the number of distinct transformations.
words = ["gin","zen","gig","msg"]2def uniqueMorseRepresentations(words):
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
seen = set()
for w in words:
seen.add(''.join(morse[ord(c) - ord('a')] for c in w))
return len(seen)
var uniqueMorseRepresentations = function(words) {
const morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
const seen = new Set();
for (const w of words) {
let t = '';
for (const c of w) t += morse[c.charCodeAt(0) - 97];
seen.add(t);
}
return seen.size;
};
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
java.util.Set<String> seen = new java.util.HashSet<>();
for (String w : words) {
StringBuilder sb = new StringBuilder();
for (char c : w.toCharArray()) sb.append(morse[c - 'a']);
seen.add(sb.toString());
}
return seen.size();
}
}
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
vector<string> morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
unordered_set<string> seen;
for (auto& w : words) {
string t;
for (char c : w) t += morse[c - 'a'];
seen.insert(t);
}
return seen.size();
}
};
Explanation
Different words can produce the same Morse string once their letters are glued together. We want to count how many distinct Morse strings appear, and a set is the perfect tool because it ignores repeats.
We keep a fixed lookup table morse where index 0 is the code for a, index 1 for b, and so on. To turn a letter into its index we use ord(c) - ord('a'), which maps a to 0, b to 1, etc.
For each word we map every letter to its code and join them into one long string, then add that string to seen. After processing all words, the answer is len(seen) — the number of unique transformations.
Example: gin becomes --..-.-. and zen becomes the exact same string, so they collapse into one entry. Likewise gig and msg match each other. Four words, but only 2 distinct codes.
Each letter is looked up in constant time, so the total work is just the combined length of all the words.