Given a string s, return the length of the longest repeating substring. If no repeating substring exists, return 0.

A repeating substring is a substring that occurs at least twice in the string.

Input & Output

Example 1 — Basic Repeating Pattern
$ Input: s = "abcabc"
Output: 3
💡 Note: The substring "abc" appears twice: at positions 0-2 and 3-5, so the longest repeating substring has length 3
Example 2 — Single Character Repetition
$ Input: s = "aabaaaba"
Output: 4
💡 Note: The substring "aaba" appears at positions 0-3 and 4-7, so the longest repeating substring has length 4
Example 3 — No Repetition
$ Input: s = "abcdef"
Output: 0
💡 Note: No substring appears more than once, so return 0

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Longest Repeating Substring - Hash Approach INPUT String s = "abcabc" a 0 b 1 c 2 a 3 b 4 c 5 Repeating Substrings: "a", "b", "c" (len=1) "ab", "bc", "ca" (len=2) "abc" (len=3) - FOUND! s = "abcabc" Length: 6 ALGORITHM STEPS 1 Binary Search Length Search len from 1 to n-1 2 Rolling Hash Compute hash for each substr 3 HashSet Check Store hashes, find duplicates 4 Update Max Length Track longest found Hash Table (len=3): "abc" --> H1 "bca" --> H2 "cab" --> H3 "abc" --> H1 DUP! Time: O(n log n), Space: O(n) FINAL RESULT Longest Repeating Substring "abc" Found at positions: a b c a b c Index 0-2 a b c a b c Index 3-5 Output: 3 OK - Length of "abc" Key Insight: Rolling hash enables O(1) substring comparison by computing hash values incrementally. Combined with binary search on length, we efficiently find the longest repeating substring in O(n log n) time instead of O(n^3). TutorialsPoint - Longest Repeating Substring | Hash Approach
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 12
35.0K Views
Medium Frequency
~25 min Avg. Time
890 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