Find Substring With Given Hash Value - Problem
Find the substring with a specific hash value in a given string.
You're given a polynomial rolling hash function that computes:
Where
Your task: Given a string
Example: If s="leetcode", power=7, modulo=20, k=2, hashValue=0, you need to find the first 2-character substring with hash value 0.
You're given a polynomial rolling hash function that computes:
hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod mWhere
val(s[i]) represents the alphabetical index of character s[i] (a=1, b=2, ..., z=26).Your task: Given a string
s and parameters power, modulo, k, and hashValue, find the first substring of length k whose hash equals hashValue.Example: If s="leetcode", power=7, modulo=20, k=2, hashValue=0, you need to find the first 2-character substring with hash value 0.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
โบ
Output:
"ee"
๐ก Note:
The hash of "ee" is (5*7^0 + 5*7^1) mod 20 = (5 + 35) mod 20 = 40 mod 20 = 0. The first substring with this hash is "ee".
example_2.py โ Different Parameters
$
Input:
s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
โบ
Output:
"fbx"
๐ก Note:
The hash of "fbx" is (6*31^0 + 2*31^1 + 24*31^2) mod 100 = (6 + 62 + 23064) mod 100 = 23132 mod 100 = 32.
example_3.py โ Edge Case
$
Input:
s = "a", power = 2, modulo = 3, k = 1, hashValue = 1
โบ
Output:
"a"
๐ก Note:
Single character case. The hash of "a" is (1*2^0) mod 3 = 1 mod 3 = 1, which matches the target.
Visualization
Tap to expand
Understanding the Visualization
1
Initial Scan
Start with the last group of suspects and get their combined fingerprint code
2
Smart Update
Move left: remove the rightmost person, add new leftmost person, update code instantly
3
Pattern Match
Compare updated code with target - if it matches, you found your suspects!
4
Efficient Search
Continue rolling left until you find the first matching group
Key Takeaway
๐ฏ Key Insight: Rolling hash transforms an O(n*k) problem into O(n) by reusing previous calculations with smart modular arithmetic updates.
Time & Space Complexity
Time Complexity
O(n)
Single pass through string with O(1) hash updates per position
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for hash calculations
โ Linear Space
Constraints
- 1 โค k โค s.length โค 2 ร 104
- 1 โค power, modulo โค 109
- 0 โค hashValue < modulo
- s consists of lowercase English letters only
- The test cases are generated such that an answer always exists
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code