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
Find Substring With Given Hash ValueInput: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0leetcodeCheck each substring of length k = 2"ee"hash = (5×1 + 5×7) % 20 = 0 ✓Output: "ee"First substring with hash value 0
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
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
28.5K Views
Medium Frequency
~35 min Avg. Time
589 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