
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.
1const uniqueMorseRepresentations = function(words) {
2 const morseMap = [
3 ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
4 ];
5 const uniqueTransformations = new Set();
6 for (const word of words) {
7 let transformation = '';
8 for (const char of word) {
9 transformation += morseMap[char.charCodeAt(0) - 97];
10 }
11 uniqueTransformations.add(transformation);
12 }
13 return uniqueTransformations.size;
14};
15
16const words = ["gin", "zen", "gig", "msg"];
17console.log(uniqueMorseRepresentations(words));The JavaScript solution uses a Set to manage unique Morse code transformations. Each word's transformation is calculated by iterating through its characters, mapping them, and joining the results. These transformations are collected in the set, and its size tells us the number of unique results.
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.
using System.Collections.Generic;
class UniqueMorseCode {
public static int UniqueMorseRepresentations(string[] words) {
string[] morseMap = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
HashSet<string> uniqueTransformations = new HashSet<string>();
foreach (string word in words) {
string transformation = "";
foreach (char c in word) {
transformation += morseMap[c - 'a'];
}
uniqueTransformations.Add(transformation);
}
return uniqueTransformations.Count;
}
static void Main() {
string[] words = { "gin", "zen", "gig", "msg" };
Console.WriteLine(UniqueMorseRepresentations(words));
}
}In this C# function, clarity reigns as Morse codes are mapped and sorted directly. Unique transformations ensue and aggregate in a HashSet, capturing quantity sans duplicates.