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
You"abab""abab" (echo)EchoFound matching echo! Length = 4
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only storing the maximum length, no extra data structures

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of only lowercase English letters
  • Time limit: 2 seconds
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.4K Views
Medium Frequency
~25 min Avg. Time
875 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen