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:
hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m

Where 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
๐Ÿ” Rolling Hash Detective Scanner๐Ÿ‘ค๐Ÿ‘ค๐Ÿ‘คFingerprint Code: 42Scanner Updates+ Add- Remove๐ŸŽฏ Key: Update fingerprint in O(1) time!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for hash calculations

n
2n
โœ“ 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
Asked in
Google 42 Meta 38 Amazon 35 Microsoft 28
38.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen