|
| 1 | +# 2156. Find Substring With Given Hash Value |
| 2 | +The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function: |
| 3 | +* <code>hash(s, p, m) = (val(s[0]) * p<sup>0</sup> + val(s[1]) * p<sup>1</sup> + ... + val(s[k-1]) * p<sup>k-1</sup>) mod m</code>. |
| 4 | + |
| 5 | +Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`. |
| 6 | + |
| 7 | +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`. |
| 8 | + |
| 9 | +The test cases will be generated such that an answer always **exists**. |
| 10 | + |
| 11 | +A **substring** is a contiguous non-empty sequence of characters within a string. |
| 12 | + |
| 13 | +#### Example 1: |
| 14 | +<pre> |
| 15 | +<strong>Input:</strong> s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 |
| 16 | +<strong>Output:</strong> "ee" |
| 17 | +<strong>Explanation:</strong> 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 | +</pre> |
| 20 | + |
| 21 | +#### Example 2: |
| 22 | +<pre> |
| 23 | +<strong>Input:</strong> s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 |
| 24 | +<strong>Output:</strong> "fbx" |
| 25 | +<strong>Explanation:</strong> 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. |
| 26 | +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. |
| 27 | +"fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". |
| 28 | +Note that "bxz" also has a hash of 32 but it appears later than "fbx". |
| 29 | +</pre> |
| 30 | + |
| 31 | +#### Constraints: |
| 32 | +* <code>1 <= k <= s.length <= 2 * 10<sup>4</sup></code> |
| 33 | +* <code>1 <= power, modulo <= 10<sup>9</sup></code> |
| 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 | +## Solutions (Python) |
| 39 | + |
| 40 | +### 1. Solution |
| 41 | +```Python |
| 42 | +class Solution: |
| 43 | + def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str: |
| 44 | + def val(c): return ord(c) - 96 |
| 45 | + value = 0 |
| 46 | + start = 0 |
| 47 | + |
| 48 | + for i in range(len(s) - 1, -1, -1): |
| 49 | + value = (value * power + val(s[i])) % modulo |
| 50 | + if i + k < len(s): |
| 51 | + value = (value - val(s[i + k]) * |
| 52 | + pow(power, k, modulo)) % modulo |
| 53 | + if value == hashValue: |
| 54 | + start = i |
| 55 | + |
| 56 | + return s[start:start + k] |
| 57 | +``` |
0 commit comments