Skip to the code
cf.
+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.

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 <= 3 * 10^4
  • text contains lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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