Longest Repeating Substring — LeetCode 1062 Python Solution
MediumLeetCode PremiumStringBinary SearchDynamic ProgrammingSuffix ArrayHash FunctionRolling Hash
- Problem
- #1062
- Pattern
- Monotonic Stack
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
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
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(n^2).
- What is the space complexity of LeetCode 1062. Longest Repeating Substring?
- The Python solution on this page uses O(n^2) 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.