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 "".

Input & Output

Example 1 — Basic Case
$ Input: s = "banana"
Output: "ana"
💡 Note: "ana" appears twice in "banana" at positions 1-3 and 3-5. It's the longest substring that appears more than once.
Example 2 — No Duplicates
$ Input: s = "abcd"
Output: ""
💡 Note: No substring appears more than once, so return empty string.
Example 3 — Single Character
$ Input: s = "aa"
Output: "a"
💡 Note: Character 'a' appears twice, making it the longest (and only) duplicate substring.

Constraints

  • 2 ≤ s.length ≤ 3 × 104
  • s consists of lowercase English letters.

Visualization

Tap to expand
Longest Duplicate Substring INPUT String s = "banana" b 0 a 1 n 2 a 3 n 4 a 5 Find Duplicates: "a" at [1,3,5] "an" at [1,3] "na" at [2,4] "ana" at [1,3] Length = 6 Goal: Find longest duplicate substring ALGORITHM STEPS 1 Binary Search Length Search L in [1, n-1] 2 Rolling Hash Hash substrings of len L 3 Check Duplicates Store hashes in set 4 Update Answer If found, try longer L Hash Table (L=3) "ban" h=127 "ana" h=234 [DUP!] "nan" h=189 FINAL RESULT Longest Duplicate Found: "ana" Occurrences in "banana": b a n a n a pos 1 b a n a n a pos 3 Output: "ana" OK - Length 3 is maximum No duplicate of length 4+ Key Insight: Binary Search + Rolling Hash achieves O(n log n) average complexity. Binary search finds the optimal length, while rolling hash efficiently computes substring hashes in O(1) time per position. If duplicate found at length L, try L+1; otherwise try shorter lengths. TutorialsPoint - Longest Duplicate Substring | Hash Approach
Asked in
Google 25 Facebook 20 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~35 min Avg. Time
891 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