Find Substring With Given Hash Value — LeetCode 2156 Python Solution

HardStringSliding WindowHash FunctionRolling Hash
Problem
#2156
Reading time
4 min

The 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]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.

Example

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.

Python solution

Python
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]

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2156. Find Substring With Given Hash Value is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2156. Find Substring With Given Hash Value?
LeetCode 2156. Find Substring With Given Hash Value is rated Hard on LeetCode.
What is the time complexity of LeetCode 2156. Find Substring With Given Hash Value?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 2156. Find Substring With Given Hash Value?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2156. Find Substring With Given Hash Value cover?
LeetCode 2156. Find Substring With Given Hash Value is tagged String, Sliding Window, Hash Function and Rolling Hash on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview