Embercode
✕
StringsQuick quiz

Rolling hash

6 questions. Covers Rolling hash in Python.

Questions 1 to 5 of 6

  1. 1. After the RollingHash constructor below has built the prefix and power lists for a string of length n, what does one call to hash(start, end) cost as the piece gets longer? ``python class RollingHash: def __init__(self, text, base, mod): self.mod = mod self.prefix = [0] * (len(text) + 1) self.power = [1] * (len(text) + 1) for i, ch in enumerate(text): self.prefix[i + 1] = (self.prefix[i] * base + ord(ch)) % mod self.power[i + 1] = (self.power[i] * base) % mod def hash(self, start, end): return (self.prefix[end] - self.prefix[start] * self.power[end - start]) % self.mod ``
  2. 2. What does building the prefix and power lists in the constructor cost, for a string of length n? (O(n) means the work grows in step with n.)
  3. 3. A common check first compares the two hashes of two pieces, and then compares their characters. Why is the character check still needed?
  4. 4. The hash method ends with % self.mod, and the value before that step can be negative. What does (-7) % 5 give in Python?
  5. 5. Using the RollingHash class from the first question, what does this code print? ``python rh = RollingHash('abcab', 10, 1_000_000_007) print(rh.hash(3, 5)) print(rh.hash(0, 3)) print(rh.hash(3, 5) == rh.hash(0, 2)) ``

5 question(s) left on this page.