Maximum Repeating Substring — LeetCode 1668 Python Solution

EasyStringDynamic ProgrammingString Matching
Problem
#1668
Reading time
2 min

The problem

For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence.

Example

Input
sequence = "ababc", word = "ab"
Output
2
Explanation
"abab" is a substring in "ababc".

Python solution

Python
class Solution:
    def maxRepeating(self, sequence: str, word: str) -> int:
        for k in range(len(sequence) // len(word), -1, -1):
            if word * k in sequence:
                return k

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1668. Maximum Repeating Substring is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1668. Maximum Repeating Substring?
LeetCode 1668. Maximum Repeating Substring is rated Easy on LeetCode.
What topics does LeetCode 1668. Maximum Repeating Substring cover?
LeetCode 1668. Maximum Repeating Substring is tagged String, Dynamic Programming and String Matching on LeetCode.

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