Longest Repeating Substring - Problem
Given a string s, find the length of the longest repeating substring. A repeating substring is one that appears at least twice in the string (possibly overlapping).
For example, in the string "abcabc", the substring "abc" appears twice, so the answer would be 3. In "aabaaaba", the substring "aaba" appears twice (overlapping), so the answer would be 4.
If no substring repeats, return 0.
Goal: Find the maximum length of any substring that occurs at least twice in the input string.
Input & Output
example_1.py โ Basic Repeat
$
Input:
s = "abab"
โบ
Output:
2
๐ก Note:
The substring "ab" appears twice: at positions 0-1 and 2-3. This is the longest repeating substring.
example_2.py โ Overlapping Repeat
$
Input:
s = "aabaaaba"
โบ
Output:
4
๐ก Note:
The substring "aaba" appears twice with overlap: at positions 0-3 and 4-7. Even though they overlap, they count as repeats.
example_3.py โ No Repeats
$
Input:
s = "abcdef"
โบ
Output:
0
๐ก Note:
No substring appears more than once in this string, so the answer is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Shout different phrases
Try phrases of different lengths (binary search)
2
Listen for echoes
Use rolling hash to quickly identify matching sound patterns
3
Find the longest echo
The longest phrase that echoes back is our answer
Key Takeaway
๐ฏ Key Insight: Binary search on the answer combined with rolling hash allows us to efficiently find the longest repeating substring without checking every possible substring individually.
Time & Space Complexity
Time Complexity
O(nยณ)
O(nยฒ) substrings ร O(n) to check each substring occurrence
โ Quadratic Growth
Space Complexity
O(1)
Only storing the maximum length, no extra data structures
โ Linear Space
Constraints
- 1 โค s.length โค 1000
- s consists of only lowercase English letters
- Time limit: 2 seconds
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code