mediumHashingPattern: Hashing
Count Unique String Hashes Solution
Problem Statement
Given an array of strings `words`, where each string represents a sequence of characters. Implement a hashing function that maps each string to a unique integer hash code. Your task is to return the total number of distinct hash codes generated from the given array of strings.
Examples
Example 1:
Input:["abc", "aba", "abc"]
Output:2
Explanation: The strings are "abc", "aba", and "abc". We need to generate hash codes for these. Let's assume a simple hashing function where the hash of a string is the sum of the ASCII values of its characters. For "abc", hash = 97+98+99 = 294. For "aba", hash = 97+98+97 = 292. The third string "abc" also hashes to 294. The distinct hash codes are 294 and 292. Thus, the total number of unique hash codes is 2.
Example 2:
Input:["hello", "world", "hello"]
Output:2
Explanation: The strings are "hello", "world", and "hello". Using the same hashing logic (sum of ASCII values), hash("hello") = 104+101+108+108+111 = 532. hash("world") = 119+111+114+108+100 = 552. The third string "hello" also hashes to 532. The distinct hash codes are 532 and 552. The total number of unique hash codes is 2.
Example 3:
Input:["a", "b", "c"]
Output:3
Explanation: The strings are "a", "b", and "c". hash("a") = 97. hash("b") = 98. hash("c") = 99. All hash codes are distinct. The total number of unique hash codes is 3.
Constraints
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 50
- Each words[i] consists of lowercase English letters.
- All strings in words are unique in terms of their character sequences.
Time: O(N*L) Space: O(N)
Iterate through the input array of strings. For each string, compute its hash code. Use a Set data structure to store these hash codes. Since a Set only stores unique elements, it will automatically handle duplicates. The final answer will be the size of the Set.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def count_unique_string_hashes(words):
if not words:
return 0
unique_hashes = set()
for word in words:
hash_val = 0
for char in word:
hash_val += ord(char)
unique_hashes.add(hash_val)
return len(unique_hashes)