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 ProblemInput: "banana"banana012345"ana" (indices 1-3)"ana" (indices 3-5)"ana" appears twice - longest duplicate!Output: "ana"
Understanding the Visualization
1
Input
String with potential duplicate substrings
2
Process
Find all substrings that appear 2+ times
3
Output
Return longest duplicate found
Key Takeaway
🎯 Key Insight: Use binary search on substring length combined with rolling hash for efficient duplicate detection
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