Longest Repeating Substring — LeetCode 1062 Python Solution

MediumLeetCode PremiumStringBinary SearchDynamic ProgrammingSuffix ArrayHash FunctionRolling Hash
Problem
#1062
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview