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
Asked in
Google 25 Facebook 20 Amazon 15 Microsoft 12
28.6K 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