Find Substring With Given Hash Value LeetCode solution in Python

1
# Runtime: 996 ms (Top 33.98%) | Memory: 14.1 MB (Top 94.23%)
2
class Solution:
3
def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:
4
val = lambda ch: ord(ch) - ord("a") + 1
5
hash, res, power_k = 0, 0, pow(power, k, mod)
6
for i in reversed(range(len(s))):
7
hash = (hash * power + val(s[i])) % mod
8
if i < len(s) - k:
9
hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod
10
res = i if hash == hashValue else res
11
return s[res : res + k]

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0