↓Skip to main content
  1. LeetCode/

LeetCode 2156: Find Substring With Given Hash Value

·3 mins· ·
LeetCode Hard Sliding-Window Rolling-Hash String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-01-04

  • Submissions: TLE → Accepted → TLE → Accepted

Approach
#

hash(s) = Σ val(s[i]) · p^i mod m, so the first character has weight p^0.

Sliding left to right, moving the window one step would divide every weight by p. But m need not be prime, so p may have no inverse modulo m, and division is impossible.

Sliding right to left needs only multiplication:

new hash = old hash · p + val(new left character) − val(outgoing right character) · p^k

Precompute p^k mod m with pow(p, k, m). Scanning right to left, the last (leftmost) match is the answer.

My Attempts
#

  1. TLE: slid left to right, computing weights as power ** (right - left) and doing //= power on removal, with no modulo, so the numbers kept growing. Exact integer division is correct without a modulo, but the big-integer arithmetic is too slow.
  2. AC: slid right to left with pk = pow(power, k, modulo).
  3. TLE: a rewrite computed power ** k % modulo at every step, and power ** k is a huge integer.
  4. AC: went back to precomputing it with pow.

Solution
#

class Solution:
    def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:
        n = len(s)
        pk = pow(power, k, modulo)                 # precompute once, not per step
        h = 0
        ans = 0
        for left in range(n - 1, -1, -1):
            h = (h * power + ord(s[left]) - 96) % modulo
            if left + k < n:
                h = (h - (ord(s[left + k]) - 96) * pk) % modulo
            if left + k <= n and h == hashValue:
                ans = left                         # leftmost match is updated last
        return s[ans:ans + k]

Python’s % returns a non-negative result for negative numbers, so no extra + modulo is needed after subtracting.

Complexity
#

Time O(n), space O(1) excluding the output.

Mistakes to Avoid
#

  • Sliding left to right needs division by p, but modulo may not be prime.
  • Computing power ** k every step: big integers, TLE.
  • The problem wants the first matching substring, so keep updating all the way to the leftmost when scanning right to left.

Interview Explanation
#

This hash gives the first character weight p^0, so sliding left to right would divide by p, and the modulus may not be prime, so there is no inverse. I slide right to left instead: multiply the old hash by p, add the new character, and subtract the outgoing character times p^k, precomputed with a modulo. Since the first match is wanted, I keep updating until the leftmost position. Time O(n).

Related

LeetCode 2953: Count Complete Substrings
·3 mins
LeetCode Hard Sliding-Window Hash-Table String
LeetCode 2953 note: split where neighboring letters differ by more than 2; in each segment enumerate the number of distinct letters d, slide a fixed window of d × k, and track how many letters appear exactly k times
LeetCode 30: Substring with Concatenation of All Words (Brute Force → Counting → Sliding Window)
·3 mins
LeetCode Daily Hard String Sliding-Window Two-Pointers Hash-Map Brute-Force Frequency-Counting
Three approaches: brute force, counting optimization, and sliding window over word-length offsets.
LeetCode 76: Minimum Window Substring
·3 mins
LeetCode Daily Hard String Sliding-Window Variable-Window Two-Pointers Hash-Map
LeetCode Problem Solving - Variable Size Sliding Window with Character Counting
LeetCode 1016: Binary String With Substrings Representing 1 To N
·3 mins
LeetCode Medium Sliding-Window String Bit-Manipulation Hash-Table
LeetCode 1016 note: s has at most 1000 characters, so there are few substrings of any fixed length and a large n must be False; checking from n downward fails fast, or extend up to 30 bits from each start to collect every value <= n
LeetCode 2269: Find the K-Beauty of a Number
·2 mins
LeetCode Easy Sliding-Window Math String
LeetCode 2269 note: convert the number to a string and check every length-k substring; 0 cannot be a divisor
LeetCode 1888: Minimum Number of Flips to Make the Binary String Alternating
·2 mins
LeetCode Medium Sliding-Window String Dynamic-Programming
LeetCode 1888 note: rotations become length-n windows over s + s; the window’s mismatches against 0101… are diff, and against 1010… they are n - diff