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*31²) % 100 = (6 + 62 + 23064) % 100 = 32, which matches hashValue
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 Value INPUT String s: l e e t c o d e 0 1 2 3 4 5 6 7 Parameters power = 7 modulo = 20 k = 2 hashValue = 0 Hash Formula hash(s,p,m) = (val(s[0])*p^0 + val(s[1])*p^1 + ... + val(s[k-1])*p^(k-1)) mod m ALGORITHM STEPS 1 Reverse Iteration Start from end of string to handle power calculation 2 Rolling Hash For window ending at i: h = h*p + val(s[i]) - val(s[i+k])*p^k 3 Check Hash Match If hash == hashValue, record the position 4 Return First Match Keep updating result to get leftmost substring For "ee": val('e')=5 hash = (5*7^0 + 5*7^1) mod 20 = (5 + 35) mod 20 = 40 mod 20 = 0 FINAL RESULT First matching substring found: l e e t c o d e Position: index 1 to 2 Output: "ee" Verification val('e') = 5 hash = (5*1 + 5*7) mod 20 = 40 mod 20 = 0 [OK] Key Insight: Iterate from RIGHT to LEFT to efficiently compute rolling hash. The power factor p^(k-1) is constant, so we can multiply hash by p and adjust. This avoids recalculating the entire hash for each window. Time complexity: O(n) where n is the length of string s. TutorialsPoint - Find Substring With Given Hash Value | Rolling Hash Approach
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