Longest Repeating Substring Problem
Description
LeetCode Problem 1062.
Given a string s, return the length of the longest repeating substrings. If no repeating substring exists, return 0.
Example 1:
Input: s = "abcd"
Output: 0
Explanation: There is no repeating substring.
Example 2:
Input: s = "abbaba"
Output: 2
Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice.
Example 3:
Input: s = "aabcaabdaab"
Output: 3
Explanation: The longest repeating substring is "aab", which occurs 3 times.
Constraints:
1 <= s.length <= 2000sconsists of lowercase English letters.
Solution
Approach: Dynamic Programming on Common Suffixes
A substring that repeats has two occurrences that end at different positions j < i. The longest such pair of occurrences ending at j and i is the longest common suffix of the prefixes s[0..j] and s[0..i]. Call its length f[i][j]:
- if
s[i] != s[j], thenf[i][j] = 0; - otherwise
f[i][j] = f[i - 1][j - 1] + 1, or1whenj = 0.
The answer is the largest f[i][j] over all j < i. The two occurrences may overlap: in "aaaa", f[3][2] = 3 is the repeated substring "aaa" at positions 0 and 1, which is allowed.
Row i only depends on row i - 1, so one array dp of length n is enough. The trick is to update j from right to left: when we compute dp[j], the entry dp[j - 1] to its left still holds the value from row i - 1.
Complexity: O(n2) time and O(n) extra space.
class Solution:
def longestRepeatingSubstring(self, s: str) -> int:
n = len(s)
# For the current i, dp[j] (j < i) is the length of the longest common
# suffix of s[:i + 1] and s[:j + 1]: two copies ending at j and at i.
dp = [0] * n
ans = 0
for i in range(1, n):
# Right to left, so dp[j - 1] still holds the value for i - 1.
for j in range(i - 1, -1, -1):
if s[i] == s[j]:
dp[j] = dp[j - 1] + 1 if j > 0 else 1
if dp[j] > ans:
ans = dp[j]
else:
dp[j] = 0
return ans