
Sponsored
Sponsored
We can utilize a HashSet data structure to store the unique transformations. For each word, we can generate its Morse code transformation by replacing each character by its corresponding Morse code. We then add each transformation to the HashSet to automatically handle duplicates. The size of the HashSet at the end gives us the number of unique transformations.
Time Complexity: O(N), where N is the total number of characters across all words.
Space Complexity: O(WL), where W is the number of words and L is the length of the longest word, due to storing transformations.
We use a simple array to act as a HashSet. First, we define the mappings from characters to Morse code. We then iterate through each word, building its Morse code transformation. Each transformation is hashed and compared to our set of seen hashes. If a hash is not seen before, it is added to the array. This method ensures that we only count unique transformations.
In this method, we establish a direct mapping of characters to Morse code using a fixed array index, which simplifies the translation process by utilizing the ASCII value difference between 'a' and the current character. We then use the translated words to populate a set directly, ensuring uniqueness of each transformation.
Time Complexity: O(N^2), due to checking each transformation against existing ones in the list.
Space Complexity: O(WL), where W is the word count and L is the length of the longest word, needed to store transformations.
1const uniqueMorseRepresentations = function(words) {
2 const morseMap = [
3 ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
4 ];
5 const uniqueTransformations = new Set();
6
7 for (const word of words) {
8 let transformation = '';
9 for (const char of word) {
10 transformation += morseMap[char.charCodeAt(0) - 97];
11 }
12 uniqueTransformations.add(transformation);
13 }
14
15 return uniqueTransformations.size;
16};
17
18const words = ["gin", "zen", "gig", "msg"];
19console.log(uniqueMorseRepresentations(words));This concise JavaScript implementation congregates Morse letters, directly utilizing a JavaScript Set to distinguish unique Morse transformations without redundancy.