HardNo. 1044
Longest Duplicate Substring — LeetCode 1044 Python Solution
- Pattern
- Sliding Window
- Topics
- String, Binary Search, Suffix Array, Sliding Window, Hash Function, Rolling Hash
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1044. Longest Duplicate Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2156 | Find Substring With Given Hash Value | Hard |
| 1208 | Get Equal Substrings Within Budget | Medium |
| 2024 | Maximize the Confusion of an Exam | Medium |
| 1234 | Replace the Substring for Balanced String | Medium |
| 1456 | Maximum Number of Vowels in a Substring of Given Length | Medium |
| 1839 | Longest Substring Of All Vowels in Order | Medium |
Frequently asked questions
- How hard is LeetCode 1044. Longest Duplicate Substring?
LeetCode 1044. Longest Duplicate Substring is rated Hard on LeetCode.
- What topics does LeetCode 1044. Longest Duplicate Substring cover?
LeetCode 1044. Longest Duplicate Substring is tagged String, Binary Search, Suffix Array, Sliding Window, Hash Function and Rolling Hash on LeetCode.