#1044

Longest Duplicate Substring

Hard Binary search + Rabin-Karp

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return any longest substring that appears at least twice in s (occurrences may overlap), or "" if none.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest piece that appears at least twice.

Why this works: if a length-L duplicate exists, shorter ones do too, so binary search L. For each L, rolling hashes find repeated windows quickly.

Example: "banana"

L=3: "ana" appears at 1 and 3 ✓L=4: "bana","anan","nana" all different ✗answer "ana"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Trusting hashes without verifying — collisions give wrong answers on big tests.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n) on average.
  • Space: O(n).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon