The "Unique Morse Code Words" problem asks you to determine how many unique Morse code transformations exist among a given list of words.
Specifically, you are given an array words
where each element is a string consisting of lowercase English letters. Each letter can be converted to a Morse code string based on the international Morse code table. You must:
words
into its Morse code representation by replacing each letter with its corresponding Morse code symbol and concatenating the results.To solve this problem, the main challenge is efficiently counting the number of unique Morse code transformations. Let's break down the steps:
Let's outline the steps to solve the problem:
Let's walk through an example with the following input:
words = ["gin", "zen", "gig", "msg"]
Step-by-step:
Brute-force approach:
class Solution:
def uniqueMorseRepresentations(self, words):
morse = [
".-","-...","-.-.","-..",".","..-.","--.","....","..",
".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-","-.--","--.."
]
seen = set()
for word in words:
code = ''.join(morse[ord(c) - ord('a')] for c in word)
seen.add(code)
return len(seen)
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
vector<string> morse = {
".-","-...","-.-.","-..",".","..-.","--.","....","..",
".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-","-.--","--.."
};
unordered_set<string> seen;
for (const string& word : words) {
string code;
for (char c : word) {
code += morse[c - 'a'];
}
seen.insert(code);
}
return seen.size();
}
};
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = {
".-","-...","-.-.","-..",".","..-.","--.","....","..",
".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-","-.--","--.."
};
Set<String> seen = new HashSet<>();
for (String word : words) {
StringBuilder code = new StringBuilder();
for (char c : word.toCharArray()) {
code.append(morse[c - 'a']);
}
seen.add(code.toString());
}
return seen.size();
}
}
var uniqueMorseRepresentations = function(words) {
const morse = [
".-","-...","-.-.","-..",".","..-.","--.","....","..",
".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-","-.--","--.."
];
const seen = new Set();
for (let word of words) {
let code = '';
for (let c of word) {
code += morse[c.charCodeAt(0) - 'a'.charCodeAt(0)];
}
seen.add(code);
}
return seen.size;
};
The Unique Morse Code Words problem is a classic example of mapping and deduplication. By translating each word into its Morse code representation and storing these in a set, we efficiently count the number of unique transformations. The solution leverages a simple mapping array for fast lookup and a set for uniqueness, making the approach both elegant and efficient. This method avoids unnecessary comparisons and demonstrates the power of combining data structures for clean solutions.