Skip to contentKEEP THE CRAFTTHE SANCTUARY

Roll a Window Hash

Compute the polynomial hash of every fixed-size window, sliding from one window to the next in O(1) the way Rabin-Karp does.

The problem

Rolling hashes are the engine of the Rabin-Karp string search. Implement rolling_window_hashes(text, window_size, base, modulus) and return the hash of every window of window_size consecutive characters, from left to right. The hash of a window c0 c1 ... c(k-1) is (ord(c0) * base^(k-1) + ord(c1) * base^(k-2) + ... + ord(c(k-1))) % modulus, where k = window_size. Example: for "abcd" with window_size = 2, base = 31 and modulus = 1000, the windows are "ab", "bc" and "cd", and the answer is [105, 137, 169]. For "ab": 97 * 31 + 98 = 3105, and 3105 % 1000 = 105. Compute each new hash from the previous one in O(1) instead of rehashing the whole window. Inputs satisfy 1 <= window_size <= len(text) and modulus > 0.

Starter code

def rolling_window_hashes(text, window_size, base, modulus):
    pass

Public examples

  1. text = "abcd", window_size = 2, base = 31, modulus = 1000gives[105, 137, 169]
  2. text = "abc", window_size = 3, base = 31, modulus = 1000gives[354]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.