Leetcode #1044: Longest Duplicate Substring
In this guide, we solve Leetcode #1044 Longest Duplicate Substring in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: String, Binary Search, Suffix Array, Sliding Window, Hash Function, Rolling Hash
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: s = "banana"
Output: "ana"
Python Solution
class Solution:
def longestDupSubstring(self, s: str) -> str:
def check(l):
vis = set()
for i in range(n - l + 1):
t = s[i : i + l]
if t in vis:
return t
vis.add(t)
return ''
n = len(s)
left, right = 0, n
ans = ''
while left < right:
mid = (left + right + 1) >> 1
t = check(mid)
ans = t or ans
if t:
left = mid
else:
right = mid - 1
return ans
Complexity
The time complexity is O(n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.