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]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-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 firstsubstring 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.
Example 1:
Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
Output: "ee"
Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0.
"ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".
Example 2:
Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
Output: "fbx"
Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32.
The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32.
"fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".
Note that "bxz" also has a hash of 32 but it appears later than "fbx".
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.
Problem summary: 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]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
How can we update the hash value efficiently while iterating instead of recalculating it each time?
Use the rolling hash method.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2156: Find Substring With Given Hash Value
class Solution {
public String subStrHash(String s, int power, int modulo, int k, int hashValue) {
long h = 0, p = 1;
int n = s.length();
for (int i = n - 1; i >= n - k; --i) {
int val = s.charAt(i) - 'a' + 1;
h = ((h * power % modulo) + val) % modulo;
if (i != n - k) {
p = p * power % modulo;
}
}
int j = n - k;
for (int i = n - k - 1; i >= 0; --i) {
int pre = s.charAt(i + k) - 'a' + 1;
int cur = s.charAt(i) - 'a' + 1;
h = ((h - pre * p % modulo + modulo) * power % modulo + cur) % modulo;
if (h == hashValue) {
j = i;
}
}
return s.substring(j, j + k);
}
}
// Accepted solution for LeetCode #2156: Find Substring With Given Hash Value
func subStrHash(s string, power int, modulo int, k int, hashValue int) string {
h, p := 0, 1
n := len(s)
for i := n - 1; i >= n-k; i-- {
val := int(s[i] - 'a' + 1)
h = (h*power%modulo + val) % modulo
if i != n-k {
p = p * power % modulo
}
}
j := n - k
for i := n - k - 1; i >= 0; i-- {
pre := int(s[i+k] - 'a' + 1)
cur := int(s[i] - 'a' + 1)
h = ((h-pre*p%modulo+modulo)*power%modulo + cur) % modulo
if h == hashValue {
j = i
}
}
return s[j : j+k]
}
# Accepted solution for LeetCode #2156: Find Substring With Given Hash Value
class Solution:
def subStrHash(
self, s: str, power: int, modulo: int, k: int, hashValue: int
) -> str:
h, n = 0, len(s)
p = 1
for i in range(n - 1, n - 1 - k, -1):
val = ord(s[i]) - ord("a") + 1
h = ((h * power) + val) % modulo
if i != n - k:
p = p * power % modulo
j = n - k
for i in range(n - 1 - k, -1, -1):
pre = ord(s[i + k]) - ord("a") + 1
cur = ord(s[i]) - ord("a") + 1
h = ((h - pre * p) * power + cur) % modulo
if h == hashValue:
j = i
return s[j : j + k]
// Accepted solution for LeetCode #2156: Find Substring With Given Hash Value
/**
* [2156] Find Substring With Given Hash Value
*
* 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^0 + val(s[1]) * p^1 + ... + 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.
*
* Example 1:
*
* Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
* Output: "ee"
* Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0.
* "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".
*
* Example 2:
*
* Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
* Output: "fbx"
* Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 31^2) mod 100 = 23132 mod 100 = 32.
* The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 31^2) mod 100 = 25732 mod 100 = 32.
* "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".
* Note that "bxz" also has a hash of 32 but it appears later than "fbx".
*
*
* Constraints:
*
* 1 <= k <= s.length <= 2 * 10^4
* 1 <= power, modulo <= 10^9
* 0 <= hashValue < modulo
* s consists of lowercase English letters only.
* The test cases are generated such that an answer always exists.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/find-substring-with-given-hash-value/
// discuss: https://leetcode.com/problems/find-substring-with-given-hash-value/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn sub_str_hash(s: String, power: i32, modulo: i32, k: i32, hash_value: i32) -> String {
String::new()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2156_example_1() {
let s = "leetcode".to_string();
let power = 7;
let modulo = 20;
let k = 2;
let hash_value = 0;
let result = "ee".to_string();
assert_eq!(
Solution::sub_str_hash(s, power, modulo, k, hash_value),
result
);
}
#[test]
#[ignore]
fn test_2156_example_2() {
let s = "fbxzaad".to_string();
let power = 31;
let modulo = 100;
let k = 3;
let hash_value = 32;
let result = "ee".to_string();
assert_eq!(
Solution::sub_str_hash(s, power, modulo, k, hash_value),
result
);
}
}
// Accepted solution for LeetCode #2156: Find Substring With Given Hash Value
function subStrHash(
s: string,
power: number,
modulo: number,
k: number,
hashValue: number,
): string {
let h: bigint = BigInt(0),
p: bigint = BigInt(1);
const n: number = s.length;
const mod = BigInt(modulo);
for (let i: number = n - 1; i >= n - k; --i) {
const val: bigint = BigInt(s.charCodeAt(i) - 'a'.charCodeAt(0) + 1);
h = (((h * BigInt(power)) % mod) + val) % mod;
if (i !== n - k) {
p = (p * BigInt(power)) % mod;
}
}
let j: number = n - k;
for (let i: number = n - k - 1; i >= 0; --i) {
const pre: bigint = BigInt(s.charCodeAt(i + k) - 'a'.charCodeAt(0) + 1);
const cur: bigint = BigInt(s.charCodeAt(i) - 'a'.charCodeAt(0) + 1);
h = ((((h - ((pre * p) % mod) + mod) * BigInt(power)) % mod) + cur) % mod;
if (Number(h) === hashValue) {
j = i;
}
}
return s.substring(j, j + k);
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(k)
Approach Breakdown
BRUTE FORCE
O(n × k) time
O(1) space
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
SLIDING WINDOW
O(n) time
O(k) space
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Shortcut: Each element enters and exits the window once → O(n) amortized, regardless of window size.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Shrinking the window only once
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.