Sub topic 13
Longest Repeated Substring with Binary Search and Hashing
This chapter assumes you already know the material from earlier chapters: the polynomial hash, prefix-hash tables that give any substring's hash in O(1), why every hash match must be verified, and how to choose a random base under a large prime modulus. It also assumes you know binary search over integers.
The problem: given a string s of length n, find the longest substring that occurs at least twice. The two occurrences may overlap. For "banana" the answer is "ana", found at indexes 1 and 3. For "aaaa" it is "aaa", found at indexes 0 and 1. For "abcd" no character repeats, so the answer is the empty string.
There are only O(n²) candidate substrings, so a brute-force search is easy to write. Comparing them directly costs O(n³) time. Hashing alone gets this down to about O(n²). Combining hashing with binary search on the answer length gives expected O(n log n), using about 30 lines of code.
The Key Observation: Repetition Is Monotone
Fix a length L and ask one yes/no question: does some substring of length L occur twice?
The answer is monotone in L. Suppose a substring t of length L occurs at positions j and i. Then the first L - 1 characters of t also occur at j and i. So if length L has a repeat, every shorter length does too. If length L has no repeat, no longer length has one either.
That gives a predicate that reads true, true, …, true, false, …, false as L goes from 0 to n. Binary search finds the last true value in O(log n) evaluations of the predicate.
| L | Repeat of length L in "banana"? | Example |
|---|---|---|
| 0 | yes | empty string |
| 1 | yes | "a" |
| 2 | yes | "an", "na" |
| 3 | yes | "ana" at 1 and 3 |
| 4 | no | windows "bana", "anan", "nana" are all distinct |
| 5 | no | "banan", "anana" |
Checking One Length in Expected O(n)
To test a length L, slide a window of width L across s. That gives n - L + 1 windows. Compute each window's hash in O(1) from the prefix table, and keep a dictionary from hash value to the start indexes already seen with that hash.
When a window's hash is already in the dictionary, there are two possibilities:
- The earlier window holds the same string. You have found a repeat, so return its position.
- The two windows hold different strings and collided. Record the new start index and keep going.
Comparing the two strings is what tells these cases apart. It costs O(L) per comparison, but a comparison that succeeds ends the check at once. Comparisons that fail happen only on collisions, which are rare when the base is chosen at random. So one check takes expected O(n).
The Full Algorithm
The upper bound is n - 1. A substring of length n is the whole string, and it has only one occurrence. The full implementation follows. It includes the prefix-hash helpers so it runs as shown.
import random
MOD = (1 << 61) - 1 # a Mersenne prime; Python ints never overflow
def build_prefix(s, base, mod=MOD):
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=MOD):
"""Hash of s[i:j]."""
return (h[j] - h[i] * p[j - i]) % mod
def longest_repeated(s):
n = len(s)
base = random.randrange(256, MOD - 1)
h, p = build_prefix(s, base)
def check(L):
"""Return the start of a repeated substring of length L, or -1."""
if L == 0:
return 0
seen = {}
for i in range(n - L + 1):
key = substring_hash(h, p, i, i + L)
bucket = seen.get(key)
if bucket is not None:
for j in bucket: # verify every hash match
if s[j:j + L] == s[i:i + L]:
return j
bucket.append(i) # true collision: keep both
else:
seen[key] = [i]
return -1
lo, hi, best = 0, max(n - 1, 0), 0
while lo < hi:
mid = (lo + hi + 1) // 2
start = check(mid)
if start != -1:
lo, best = mid, start
else:
hi = mid - 1
return s[best:best + lo]
for word in ["banana", "aaaa", "abcd", "mississippi", "", "x"]:
print(repr(word), "->", repr(longest_repeated(word)))Output:
'banana' -> 'ana'
'aaaa' -> 'aaa'
'abcd' -> ''
'mississippi' -> 'issi'
'' -> ''
'x' -> ''For "mississippi", "issi" occurs at indexes 1 and 4. These two occurrences overlap at index 4, which shows that overlapping repeats count.
Testing Against Brute Force
Hash-based code can look right and still have subtle bugs. Compare it with a slow reference on many random small inputs. A two-letter alphabet produces lots of repeats and edge cases.
import random
def brute_lrs_length(s):
n = len(s)
for L in range(n - 1, 0, -1):
subs = [s[i:i + L] for i in range(n - L + 1)]
if len(subs) != len(set(subs)):
return L
return 0
for _ in range(2000):
s = "".join(random.choice("ab") for _ in range(random.randint(0, 12)))
got = longest_repeated(s)
assert len(got) == brute_lrs_length(s), (s, got)
if got:
assert s.find(got) != s.rfind(got), (s, got) # really occurs twice
print("all tests passed")Run this after the previous block. It checks two things: the length matches the brute-force answer, and the returned string really appears at two different positions.
Complexity
| Step | Cost |
|---|---|
| Build prefix hashes and powers | O(n) |
| One call to `check(L)` | expected O(n): n − L + 1 O(1) hashes plus rare collision comparisons |
| Binary search iterations | O(log n) |
| Total | expected O(n log n) time, O(n) extra space |
The worst case is worse. If an adversary could force collisions, each bucket could fill with different strings, and every new window would be compared against all of them at O(L) each. Choosing the base at random after the input is fixed makes this extremely unlikely. A collision between two given strings of length L has probability at most about L / MOD, which is negligible with a 61-bit prime.
Common Errors
- Infinite loop from rounding down. With
mid = (lo + hi) // 2and the updatelo = mid, the casehi = lo + 1givesmid = loforever. Round up with(lo + hi + 1) // 2when the success branch assignslo = mid. - Slicing instead of hashing. Storing
s[i:i+L]in a Python set looks simple, but every slice and every set hash costs O(L). A check then takes O(nL), and the whole search takes O(n² log n) in the worst case. The O(1) per-window cost comes from the prefix table. - Skipping verification. As explained above, this can return a length with no real repeat. It gives no warning.
- Losing the start index. Record the start returned by the last successful check. The last length the loop tests is not always the final answer.
- Storing only one index per hash. If a collision overwrites the earlier index, a later window that really equals the overwritten one goes unnoticed. Keep a list per hash, as the code does.
Variants and Alternatives
The same pattern works for other questions about repeated substrings:
- Non-overlapping repeats. The predicate is still monotone. If two copies of length
Lstart at leastLapart, their prefixes of lengthL - 1are also at leastL - 1apart. Only the check changes. - Repeated at least k times. Count verified occurrences per distinct string and succeed when a count reaches
k. - Longest common substring of two strings. Hash all windows of length
Lin one string, then look up the windows of the other. You can also concatenate the strings with a separator and require one occurrence on each side.
Suffix arrays with an LCP array solve the plain problem deterministically, in O(n log n) or O(n) time. Suffix automata solve it in O(n). Both are harder to write correctly. Hashing with binary search is short and adapts easily to variants. Its cost is a small, controllable chance of slowdown, which verification keeps from ever becoming a wrong answer.
Exercise
Change check(L) so that it reports only non-overlapping repeats, meaning two occurrences with starts j < i and i - j >= L. Which index should you keep for each distinct string, and why does binary search remain valid?
Show answer
For each distinct string, keep only its first (smallest) start index. When window i hashes to a bucket, compare it with each stored j. If s[j:j+L] equals s[i:i+L], return j when i - j >= L. If the gap is too small, do not append i, because j is already the best partner for any later window with that string. Append i only when no stored string in the bucket equals the window, which means a true collision. Keeping the earliest j maximizes the gap, so no valid pair is missed. Binary search stays valid because the predicate is still monotone: a non-overlapping pair of length L gives a non-overlapping pair of length L - 1 at the same starts, since i - j >= L > L - 1.
Exercise
A teammate drops the string comparison in check and returns j as soon as two hashes are equal. Using a fixed base and modulus, they get correct answers on all their tests. Describe what can go wrong and in which direction the reported answer is wrong.
Show answer
A collision between two different windows of length L makes check(L) return true when no repeat of that length exists. Binary search treats that as success, sets lo to L, and searches longer lengths. The reported answer can therefore be too long, and the returned substring may occur only once. A missing repeat cannot happen, because equal strings always hash equally, so the error can only overestimate. Passing tests does not prove the code correct. With a fixed base, someone can build inputs that collide on purpose.
Exercise
For s = "abcabcab", list the lengths that binary search tests, starting from lo = 0 and hi = 7, and give the final answer.
Show answer
mid = 4: "abca" occurs at 0 and 3, so lo = 4. mid = 6: the windows "abcabc", "bcabca", "cabcab" are distinct, so hi = 5. mid = 5: "abcab" occurs at 0 and 3, so lo = 5. Now lo equals hi at 5, and the answer is "abcab", which occurs at indexes 0 and 3. The two occurrences overlap.