easyStringsPattern: Hashing
String Hash Validator Solution
Problem Statement
Given a non-empty string and a list of previously hashed strings, determine whether the input string is unique or a duplicate based on its hash value.
Examples
Example 1:
Input:hello world
Output:0
Explanation: The hash value of "hello world" is the sum of ASCII values of its characters: (104 + 101 + 108 + 108 + 111 + 32 + 87 + 111 + 114 + 108 + 100) mod 971 = 0.
Example 2:
Input:
Output:
Explanation: An empty string has no hash value.
Example 3:
Input:abc
Output:123
Explanation: The hash value of "abc" is the sum of ASCII values of its characters: (97 + 98 + 99) mod 971 = 123.
Constraints
- The input string is not empty.
- The list of previously hashed strings is not empty.
- The input string and the list of previously hashed strings only contain lowercase English letters and spaces.
Time: O(n) Space: O(m)
Use a string hashing function and a set to store previously hashed strings, and check the hash value of the input string against 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 string_hash_validator(input_string, hash_values):
hash_value = 0
for char in input_string:
hash_value = (hash_value + ord(char)) % 971
return 1 if hash_value in hash_values else 0