MediumNo. 1062LeetCode Premium
Longest Repeating Substring — LeetCode 1062 Python Solution
- Pattern
- Monotonic Stack
- Topics
- String, Binary Search, Dynamic Programming, Suffix Array, Hash Function, Rolling Hash
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return the length of the longest repeating substrings. If no repeating substring exists, return 0.
Example
- Input
- s = "abcd"
- Output
- 0
- Explanation
- There is no repeating substring.
Python solution
class Solution:
def longestRepeatingSubstring(self, s: str) -> int:
n = len(s)
f = [[0] * n for _ in range(n)]
ans = 0
for i in range(1, n):
for j in range(i):
if s[i] == s[j]:
f[i][j] = 1 + (f[i - 1][j - 1] if j else 0)
ans = max(ans, f[i][j])
return ansComplexity
- Time
- O(n2)
- Space · auxiliary
- O(n2)
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1062. Longest Repeating Substring is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1923 | Longest Common Subpath | Hard |
| 0902 | Numbers At Most N Given Digit Set | Hard |
| 0300 | Longest Increasing Subsequence | Medium |
| 0354 | Russian Doll Envelopes | Hard |
| 0410 | Split Array Largest Sum | Hard |
| 0887 | Super Egg Drop | Hard |
Frequently asked questions
- How hard is LeetCode 1062. Longest Repeating Substring?
LeetCode 1062. Longest Repeating Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1062. Longest Repeating Substring?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 1062. Longest Repeating Substring?
The Python solution on this page uses O(n2) auxiliary space.
- What topics does LeetCode 1062. Longest Repeating Substring cover?
LeetCode 1062. Longest Repeating Substring is tagged String, Binary Search, Dynamic Programming, Suffix Array, Hash Function and Rolling Hash on LeetCode.
- Is LeetCode 1062. Longest Repeating Substring a premium problem?
Yes. LeetCode 1062. Longest Repeating Substring is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.