Longest Duplicate Substring
Hard
Topics
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
Input: s = "banana" Output: "ana"
Example 2
Input: s = "abcd" Output: ""
Example 3
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
- For each length from 1 to
n-1, walk every substring of that length. - Track seen substrings in a set; on a repeat, keep the lexicographically smallest.
- If this length had a duplicate, record it as the current best.
- 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 asn-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
Noneor-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 bestimport java.util.*;
class Solution {
public String longestDupSubstring(String s) {
int n = s.length();
String best = "";
for (int len = 1; len <= n - 1; len++) {
Set<String> seen = new HashSet<>();
String found = null;
for (int i = 0; i + len <= n; i++) {
String sub = s.substring(i, i + len);
if (seen.contains(sub)) {
if (found == null || sub.compareTo(found) < 0) found = sub;
} else seen.add(sub);
}
if (found != null) best = found;
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string longestDupSubstring(string s) {
int n = s.size();
string best = "";
for (int len = 1; len <= n - 1; len++) {
unordered_set<string> seen;
bool has = false;
string found;
for (int i = 0; i + len <= n; i++) {
string sub = s.substr(i, len);
if (seen.count(sub)) {
if (!has || sub < found) {
found = sub;
has = true;
}
} else seen.insert(sub);
}
if (has) best = found;
}
return best;
}
};/**
* @param {string} s
* @return {string}
*/ var longestDupSubstring = function(s) {
const n = s.length;
let best = "";
for (let len = 1; len <= n - 1; len++) {
const seen = {};
let found = null;
for (let i = 0; i + len <= n; i++) {
const sub = s.substring(i, i + len);
if (seen[sub]) {
if (found === null || sub < found) found = sub;
} else seen[sub] = true;
}
if (found !== null) best = found;
}
return best;
};