Find Substring With Given Hash Value - Problem
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:
hash(s, p, m) = (val(s[0]) * p⁰ + val(s[1]) * p¹ + ... + val(s[k-1]) * p^(k-1)) mod m
Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.
You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.
The test cases will be generated such that an answer always exists.
A substring is a contiguous non-empty sequence of characters within a string.
Input & Output
Example 1 — Basic Case
$
Input:
s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
›
Output:
ee
💡 Note:
Hash of "ee" = (5*1 + 5*7) % 20 = 40 % 20 = 0, which matches hashValue
Example 2 — Single Character
$
Input:
s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
›
Output:
fbx
💡 Note:
Hash of "fbx" = (6*1 + 2*31 + 24*961) % 100 = 23130 % 100 = 30, continue checking until match found
Example 3 — Edge Case
$
Input:
s = "xmmhdakfursinye", power = 96, modulo = 45, k = 15, hashValue = 21
›
Output:
xmmhdakfursinye
💡 Note:
The entire string has length 15, equal to k, so only one possible substring
Constraints
- 1 ≤ k ≤ s.length ≤ 2 × 104
- 1 ≤ power, modulo ≤ 109
- 0 ≤ hashValue < modulo
- s consists of lowercase English letters only
- The answer is guaranteed to exist
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s with parameters: power, modulo, k, hashValue
2
Process
Compute hash for each substring of length k using rolling hash
3
Output
Return first substring whose hash equals hashValue
Key Takeaway
🎯 Key Insight: Rolling hash technique allows efficient O(1) hash updates when sliding the window, avoiding costly recomputation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code