Longest Duplicate Substring

Hard · Arrays & Hashing · String · Binary Search · Sliding Window · Rolling Hash · Hash Function

Problem

You are given a string s. A duplicated substring is a contiguous piece of s that occurs in it at least twice; the two occurrences may overlap.

Return any duplicated substring of the greatest possible length. If no substring occurs twice, return the empty string "".

Examples

Input: s = "mississippi"
Output: "issi"

"issi" occurs at positions 1 and 4; the two occurrences share the middle "i". Nothing longer repeats.

Input: s = "abcd"
Output: ""

Every letter is different, so no substring occurs twice.

Input: s = "aaaa"
Output: "aaa"

"aaa" occurs at positions 0 and 1.

Constraints

Approaches

Follow-up

A suffix array with its LCP array solves this in O(n log n) (or O(n) with a linear-time construction) without hashing: the longest duplicate is the largest LCP value between neighboring suffixes. A suffix automaton gives O(n) as well.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…