Python 1668.py
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
k = 0
while sequence.find(k * word) >= 0:
k += 1
return k - 1
Difficulty
and has an acceptance rate of about 40% (200k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- String
- String Matching
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a single method maxRepeating that determines the maximum number of consecutive repetitions of a substring word that can be found within a larger string sequence. The algorithm incrementally builds candidate strings consisting of word repeated k times and checks for their presence using Python’s built-in find method. The loop stops as soon as a repetition count fails to appear, and the method returns the highest successful count.
Key Steps
The method begins by initializing a counter variable:
k = 0
A while loop then drives the core logic. Inside the loop the expression k * word creates a new string formed by concatenating word to itself k times. The find method searches sequence for this constructed pattern:
while sequence.find(k * word) >= 0:
k += 1
If the pattern is found, k is incremented and the loop repeats, testing the next larger repetition. When find returns -1, indicating the pattern is absent, the loop exits. Finally, the method returns the last successful repetition count, which is k - 1:
return k - 1
Edge Cases
When word is an empty string, the expression k * word also yields an empty string for any k. Since an empty string is considered to be present at every position in sequence, find will always return 0. The loop therefore increments k indefinitely. However, Python’s integer arithmetic will eventually raise a MemoryError if the loop runs unchecked, effectively preventing an infinite loop in practice.
If sequence itself is empty, the first call to find evaluates sequence.find(0 * word), which is sequence.find(""). The empty pattern is found at index 0, so k becomes 1. The next iteration checks sequence.find("" ) again, which still succeeds, leading to the same unbounded growth as the empty-word case.
When word is longer than sequence, the first constructed pattern 0 * word is an empty string and is found, causing k to become 1. The next pattern 1 * word equals word itself, which cannot be located in a shorter sequence. The find call returns -1, the loop stops, and the method returns 0, correctly indicating that no repetition exists.
If word appears in sequence but not consecutively, the algorithm only counts consecutive repetitions because each candidate pattern must be a contiguous block of repeated word. For example, with sequence = "ababa" and word = "ab", the pattern "ab" is found, but "abab" is not, so the method returns 1.
When word consists of characters that overlap with themselves (e.g., word = "aa"), the multiplication k * word still produces the correct repeated string ("aa", "aaaa", etc.). The find method correctly identifies overlapping occurrences because it searches for the exact concatenated pattern, ensuring accurate counting of maximal consecutive repetitions.
Performance Optimizations
The algorithm leverages Python’s highly optimized C implementation of str.find, which performs fast substring searches using efficient internal heuristics. By constructing the candidate pattern with the multiplication operator, the code avoids explicit loops for building the repeated string, relying on the interpreter’s optimized string multiplication routine.
Incremental checking-testing k, then k+1, and so on-means that the search stops at the first failure, preventing unnecessary examinations of larger patterns that could never exist. This early-exit behavior reduces the total number of find calls, especially when the maximum repetition count is small relative to the length of sequence.
Because the method does not allocate auxiliary data structures beyond the temporary repeated string, memory usage stays minimal, limited to the size of the current candidate pattern. The approach thus scales well for typical input sizes where the repeated pattern does not become excessively large.
ELI5 - Simplified Explanation
Imagine a long string of colorful building blocks called sequence. Some of these blocks are put together to make a special pattern called word. This code is like a little robot helper that wants to find out how many times this pattern repeats back to back inside the big line of blocks.
The robot starts out by guessing that the pattern happens zero times. It then looks at the big line of blocks to see if the pattern is hiding there once. If the robot finds it, it makes a mark to remember one and then checks if the pattern appears twice in a row instead. The robot keeps doing this over and over, adding one more to its count each time it finds the longer chain. Eventually, the robot will try to find a chain that is too long to fit, and when it cannot find that one, it stops and realizes the last number it successfully counted is the answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | C | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1566: Detect Pattern of Length M Repeated K or More Times
- problem 3137: Minimum Number of Operations to Make Word K-Periodic
Solved On The Same Day
- problem 1013: Partition Array Into Three Parts With Equal Sum
- problem 1736: Latest Time by Replacing Hidden Digits
- problem 1784: Check if Binary String Has at Most One Segment of Ones
- problem 2099: Find Subsequence of Length K With the Largest Sum
- problem 2383: Minimum Hours of Training to Win a Competition
- problem 2511: Maximum Enemy Forts That Can Be Captured
- problem 2739: Total Distance Traveled
- problem 331: Verify Preorder Serialization of a Binary Tree
- problem 400: Nth Digit
- problem 447: Number of Boomerangs
- problem 1476: Subrectangle Queries
- problem 1828: Queries on Number of Points Inside a Circle
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality