Sub topic 13
Longest Repeated Substring with Binary Search and Hashing
This chapter assumes you know the prefix-hash tables from the earlier chapter, where substring_hash returns the hash of s[i:j] in O(1) time. It also assumes you can write a binary search over integers and know that a hash match must be checked by direct comparison before you trust it.
The problem
Given a string s, find the longest substring that occurs at least twice. The two occurrences may overlap. In "banana" the answer is "ana", found at index 1 and index 3.
A brute-force approach compares every pair of starting positions for every length. That costs O(n³) character comparisons, or O(n²) with extra cleverness. Hashing plus binary search brings the expected cost down to O(n log n).
Why binary search works
Binary search needs a yes/no question whose answer flips only once as the input grows. Here the question is: "Does some substring of length L occur twice?"
That answer is monotone. Suppose a substring of length L repeats at positions i and j. Then its first L − 1 characters also repeat at i and j. So if the answer is yes for L, it is yes for every shorter length. If it is no for L, it is no for every longer length. This lets us binary search for the largest L that gets a yes.
Checking one length in O(n)
For a fixed L, slide over every window of length L. Get each window's hash from the prefix table and store it in a dictionary that maps hash to start positions. If a new window's hash is already in the dictionary, compare the actual characters to rule out a collision.
Implementation
def build_prefix(s, base=256, mod=1_000_000_007):
h = [0] * (len(s) + 1)
p = [1] * (len(s) + 1)
for i, ch in enumerate(s):
h[i + 1] = (h[i] * base + ord(ch)) % mod
p[i + 1] = (p[i] * base) % mod
return h, p
def substring_hash(h, p, i, j, mod=1_000_000_007):
return (h[j] - h[i] * p[j - i]) % mod
def repeat_of_length(s, L, h, p):
"""Return the start of a length-L substring that occurs twice, or -1."""
seen = {}
for i in range(len(s) - L + 1):
key = substring_hash(h, p, i, i + L)
for j in seen.get(key, []):
if s[j:j + L] == s[i:i + L]: # verify: rule out collisions
return i
seen.setdefault(key, []).append(i)
return -1
def longest_repeated(s):
h, p = build_prefix(s)
lo, hi, best = 1, len(s) - 1, ""
while lo <= hi:
mid = (lo + hi) // 2
pos = repeat_of_length(s, mid, h, p)
if pos >= 0:
best = s[pos:pos + mid]
lo = mid + 1
else:
hi = mid - 1
return best
print(longest_repeated("banana")) # ana
print(longest_repeated("abcd")) # (empty string)
print(longest_repeated("mississippi")) # issiCost and common errors
Building the prefix table costs O(n). Each check costs O(n) expected time, and binary search runs about log₂ n checks, so the expected total is O(n log n). Each check also stores up to n hashes, so it uses O(n) memory.
| Mistake | Effect |
|---|---|
| Returning on hash equality without comparing characters | A collision produces a substring that does not actually repeat |
| Setting `hi = len(s)` | A length-n substring can occur only once, so that check is wasted work |
| Keeping one position per hash | A collision can hide a real repeat that shares the same hash |
| Using a fixed, known modulus on untrusted input | Crafted strings force collisions, and verification work grows toward O(n²) |
Exercise
What does longest_repeated("aaaa") return, and why can the two occurrences overlap?
Show answer
It returns "aaa", which occurs at index 0 and index 1. The definition only requires two different start positions, so the occurrences may share characters. The check for L = 3 finds a repeat and the check for L = 4 cannot (there is only one window), so the binary search settles on 3.
Exercise
Why would binary search give wrong answers if the question were "does some substring of length exactly L occur exactly twice?"
Show answer
That question is not monotone. In "aaaa", length 3 occurs exactly twice but length 2 occurs three times, so the answer is no for 2 and yes for 3. Binary search needs every length shorter than a yes length to also be a yes.