#2156

Find Substring With Given Hash Value

Hard
StringSliding WindowRolling HashHash FunctionRolling HashSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a rolling hash technique, which allows us to efficiently update the hash value as we slide over the string. Instead of recalculating the hash from scratch for each substring, we adjust the hash based on the characters that enter and exit the window.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the initial hash for the first substring of length k.
  2. 2Step 2: Use a loop to slide the window one character at a time from the start to the end of the string.
  3. 3Step 3: For each new position, update the hash by removing the contribution of the character that is sliding out and adding the contribution of the character that is sliding in.
  4. 4Step 4: If the updated hash matches hashValue, return the current substring.
solution.py16 lines
1def findSubstring(s, power, modulo, k, hashValue):
2    n = len(s)
3    current_hash = 0
4    for i in range(k):
5        current_hash = (current_hash + (ord(s[i]) - ord('a') + 1) * (power ** i)) % modulo
6    if current_hash == hashValue:
7        return s[:k]
8    power_k = power ** (k - 1)
9    for i in range(k, n):
10        current_hash = (current_hash - (ord(s[i - k]) - ord('a') + 1) * power_k) % modulo
11        current_hash = (current_hash * power + (ord(s[i]) - ord('a') + 1)) % modulo
12        if current_hash < 0:
13            current_hash += modulo
14        if current_hash == hashValue:
15            return s[i - k + 1:i + 1]
16    return ''

Complexity note: The time complexity is O(n) because we only make a single pass through the string, updating the hash in constant time for each character.

  • 1Using a rolling hash allows for efficient updates instead of recalculating the hash from scratch.
  • 2Understanding the mathematical properties of modular arithmetic is crucial for hash calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.