2156. Find Substring With Given Hash Value Hard

@problem@discussion
#String#Sliding Window#Rolling Hash#Hash Function



1/**
2 * [2156] Find Substring With Given Hash Value
3 *
4 * The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:
5 * 
6 * 	hash(s, p, m) = (val(s[0]) * p^0 + val(s[1]) * p^1 + ... + val(s[k-1]) * p^k-1) mod m.
7 * 
8 * Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.
9 * 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.
10 * The test cases will be generated such that an answer always exists.
11 * A substring is a contiguous non-empty sequence of characters within a string.
12 *  
13 * Example 1:
14 * 
15 * Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
16 * Output: "ee"
17 * Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. 
18 * "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".
19 * 
20 * Example 2:
21 * 
22 * Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
23 * Output: "fbx"
24 * 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. 
25 * 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. 
26 * "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".
27 * Note that "bxz" also has a hash of 32 but it appears later than "fbx".
28 * 
29 *  
30 * Constraints:
31 * 
32 * 	1 <= k <= s.length <= 2 * 10^4
33 * 	1 <= power, modulo <= 10^9
34 * 	0 <= hashValue < modulo
35 * 	s consists of lowercase English letters only.
36 * 	The test cases are generated such that an answer always exists.
37 * 
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/find-substring-with-given-hash-value/
42// discuss: https://leetcode.com/problems/find-substring-with-given-hash-value/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47    pub fn sub_str_hash(s: String, power: i32, modulo: i32, k: i32, hash_value: i32) -> String {
48        String::new()
49    }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_2156() {
60    }
61}
62


Back
© 2025 bowen.ge All Rights Reserved.