Longest Duplicate Substring Problem
Description
LeetCode Problem 1044.
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".
Example 1:
Input: s = "banana"
Output: "ana"
Example 2:
Input: s = "abcd"
Output: ""
Constraints:
2 <= s.length <= 3 * 10^4sconsists of lowercase English letters.
Solution
Approach: Binary Search + Rabin-Karp
If some substring of length L occurs twice, then so does its prefix of length L - 1. So the lengths that have a duplicate form a range 0..best, and we can binary search for best.
For a fixed length L, we need to know whether two windows of that length are equal. Comparing every window as a string costs O(n * L). Instead use a rolling hash (Rabin-Karp): treat a window as a number in base 31 modulo a large prime. Moving the window one step to the right removes the first letter's contribution (code * 31^(L-1)), multiplies by 31 and adds the new letter, all in O(1).
Store each hash with the start positions that produced it. When a new window's hash is already in the table, compare the actual text with those earlier windows before accepting it: different strings can share a hash, and without this check a collision would give a wrong answer.
The binary search remembers where the last successful length was found, and the answer is that substring (an empty string if no length works).
Any longest duplicated substring is accepted, so the judge checks that the returned string really occurs twice and compares its length.
Complexity: O(n log n) expected time and O(n) space.
class Solution:
def longestDupSubstring(self, s: str) -> str:
n = len(s)
MOD, BASE = 10 ** 9 + 7, 31
codes = [ord(c) - ord('a') + 1 for c in s]
def find(length: int) -> int:
# Start of a substring of this length that occurs twice, or -1 (Rabin-Karp rolling hash).
power = pow(BASE, length - 1, MOD)
h = 0
for i in range(length):
h = (h * BASE + codes[i]) % MOD
starts = {h: [0]}
for i in range(1, n - length + 1):
h = ((h - codes[i - 1] * power) * BASE + codes[i + length - 1]) % MOD
if h in starts:
# Equal hashes can still be a collision, so compare the actual text.
piece = s[i:i + length]
if any(s[j:j + length] == piece for j in starts[h]):
return i
starts[h].append(i)
else:
starts[h] = [i]
return -1
# If a length works, every shorter one works too, so binary search on the length.
lo, hi, start = 0, n - 1, 0
while lo < hi:
mid = (lo + hi + 1) // 2
i = find(mid)
if i >= 0:
lo, start = mid, i
else:
hi = mid - 1
return s[start:start + lo]