Longest Duplicate Substring

Hard

Topics
StringBinary SearchSuffix ArrayRolling Hash

Given a string s, consider all duplicated substrings: (contiguous) substrings that occur two or more times (the occurrences may overlap). Return the longest such substring; if there are several of the maximum length, return the lexicographically smallest one. If none exists, return "".

Example 1

b0a1n2a3n4a5
Input:  s = "banana"
Output: "ana"

Example 2

a0b1c2d3
Input:  s = "abcd"
Output: ""

Example 3

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

Constraints

  • 1 <= s.length <= 16
  • s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A duplicated substring is one that occurs at two different starting positions, and the occurrences may overlap — "aaaa" contains "aaa" at indices 0 and 1. That overlap allowance is why the longest candidate has length n-1 rather than n/2, and it is where the loop bound comes from.

The shown solution scans lengths from short to long, collecting substrings of each length in a set and keeping the lexicographically smallest that repeats. Because longer lengths overwrite shorter ones, the final answer is the longest length that had any duplicate at all.

At the stated bound of 16 characters this is the right amount of machinery. The real version of this problem has strings of 3×10⁴, where the answer is binary search on the length combined with Rabin-Karp rolling hashes — monotone because if a duplicate of length L exists, so does one of every shorter length.

Approach

  1. For each length from 1 to n-1, walk every substring of that length.
  2. Track seen substrings in a set; on a repeat, keep the lexicographically smallest.
  3. If this length had a duplicate, record it as the current best.
  4. Return the last recorded best, or the empty string.

Dry Run

s = "banana"

  len  substrings of that length         duplicate kept
  1    b a n a n a                       a
  2    ba an na an na                    an
  3    ban ana nan ana                   ana
  4    bana anan nana                    --
  5    banan anana                       --

answer "ana"   the longest length that still had a duplicate

  "abcd"   -> ""      no substring repeats
  "aaaa"   -> "aaa"   occurrences at indices 0 and 1 overlap, which is allowed
  "aababa" -> "aba\"

Complexity

  • Time — O(n³): O(n) lengths, O(n) substrings each, O(n) to hash or compare a substring.
  • Space — O(n²) substrings held in the set per length, O(n³) characters in total.
  • Binary search on the length with rolling hashes is O(n log n) expected, which is what the problem wants at scale; a suffix automaton or suffix array with LCP gives O(n) or O(n log n) deterministically.

Common Pitfalls

  • Stopping the length loop at n/2. Overlapping occurrences are permitted, so a duplicate can be as long as n-1 — "aaaa" is the counterexample.
  • Returning the first duplicate found at the best length rather than the lexicographically smallest. The problem breaks ties by order, so every duplicate at that length must be compared.
  • Scanning lengths downward and returning immediately. That is correct and faster, but only if the tie-break is still applied within the length — returning the first hit skips it.
  • Assuming the duplicate lengths are not monotone. They are, which is what licenses binary search in the scaled-up version, and it is worth stating because the monotonicity is not about the string's content.
  • Using a hash set of rolling hashes without verifying a collision. At interview scale a 64-bit double hash is accepted, but the verification step is what makes the answer honest rather than probably-right.
  • Returning the empty string as None or -1. The specified answer for "no duplicate" is the empty string.

Full Solution — all languages

class Solution:
    def longestDupSubstring(self, s):
        n = len(s)
        best = ""
        for length in range(1, n):
            seen = set()
            found = None
            i = 0
            while i + length <= n:
                sub = s[i:i + length]
                if sub in seen:
                    if found is None or sub < found:
                        found = sub
                else:
                    seen.add(sub)
                i += 1
            if found is not None:
                best = found
        return best
SensAI
Beta
Tap the mic to stop voice mode