Skip to the code
+50 XP

#618 Longest Duplicated Fragment

hard

The copy-paste detector now wants the single longest fragment that appears at least twice in a file. Occurrences may overlap, so in aaaa the answer is aaa.

Write longestDuplicate(text) that returns that fragment. If several fragments share the longest length, return the one whose first appearance is earliest. If no character repeats at all, return an empty string.

Files can be 100,000 characters long, so comparing every pair of positions is far too slow.

Example 1

Input: text = "banana"
Output: "ana"

ana appears at index 1 and index 3 (overlapping).

Example 2

Input: text = "abcd"
Output: ""

No fragment appears twice.

Constraints

  • 0 <= text.length <= 10^5
  • text contains lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).