Problem 1668

Abstract / Summary

Find the longest substring that can be repeated the most times without overlapping in the given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
6 lines | 181 bytes | submitted October 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (200k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • String
  • String Matching
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.96 | σ = 1.32

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 15 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

13 solutions   October 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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