TRT
Sign in
hardAdvancedLeetCode#suffix array with LCP#binary search on length with rolling hash

Longest duplicate substring

Find the longest substring that occurs at least twice, with a suffix array and LCP array, or binary search over rolling hashes.

The Runtime Theory Team1 min read
Taught inSuffix arrays in practicePro — members onlyA suffix array lists the starting positions of a text's suffixes in sorted order. With the LCP array beside it, it answers substring search, repeated substrings and distinct-substring counts, and it underlies genome search tools.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = "banana"

out"ana"

ins = "abcd"

out""

ins = "aa"

out"a"

Return any longest substring of s that occurs at least twice; occurrences may overlap. If no substring repeats, return the empty string. s can have up to 30,000 characters.

Before you code

Every repeated substring is a common prefix of two suffixes. Which two suffixes, after sorting, share the longest prefix?

Hints

  1. Suffix array approach: build the suffix array by prefix doubling, then the LCP array with Kasai's algorithm. The largest LCP value and its position give the answer.
  2. Hashing approach: if a substring of length L repeats, so does one of every shorter length. Binary search on L, and for each L, roll a hash over all windows and look for a repeat.
  3. With hashing, verify a candidate repeat by comparing the substrings, or use two moduli, since a collision would return a wrong answer.

Production & complexity notes

When solving Longest duplicate substring on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Suffix arrays in practice to reinforce the underlying pattern.

What it practices

The LCP array, from Suffix arrays in practice, and binary search over rolling hashes, from Rolling hash and Rabin-Karp.

Not started

Sign in to save your learning progress.

Sign in to save