Maximum Repeating Substring - Problem
Maximum Repeating Substring
Given two strings
A string
Your task is to return the highest value k where
Example:
•
• Because
Given two strings
sequence and word, you need to find the maximum k-repeating value of word in sequence.A string
word is k-repeating if word concatenated k times is a substring of sequence. For example, if word = "ab" and sequence = "ababab", then word is 3-repeating because "ab" + "ab" + "ab" = "ababab" is found in the sequence.Your task is to return the highest value k where
word repeated k times appears as a substring in sequence. If word is not a substring of sequence at all, return 0.Example:
•
sequence = "ababc", word = "ab" → return 2• Because
"abab" (ab repeated 2 times) is in sequence, but "ababab" is not Input & Output
example_1.py — Basic Case
$
Input:
sequence = "ababc", word = "ab"
›
Output:
2
💡 Note:
The word "ab" repeats 2 times as "abab" which is found in "ababc". "ab" repeated 3 times would be "ababab" which is not found in the sequence.
example_2.py — No Repetition
$
Input:
sequence = "ababc", word = "ba"
›
Output:
1
💡 Note:
The word "ba" appears once in "ababc" but "baba" does not appear, so maximum k is 1.
example_3.py — Word Not Found
$
Input:
sequence = "ababc", word = "ac"
›
Output:
0
💡 Note:
The word "ac" is not found in "ababc" at all, so the maximum k-repeating value is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Start with single word
Begin by looking for the word once in the sequence
2
Extend the pattern
Add the word to our pattern and check if this longer repetition exists
3
Continue until failure
Keep extending until we can't find the pattern anymore
4
Return maximum found
The last successful k value is our answer
Key Takeaway
🎯 Key Insight: By building the pattern incrementally and stopping at the first failure, we efficiently find the maximum repetitions without unnecessary work.
Time & Space Complexity
Time Complexity
O(n * k)
Where n = len(sequence), k = actual maximum repeats. We do k substring searches, each taking O(n) time
✓ Linear Growth
Space Complexity
O(k * m)
Space for the repeated word string, which grows to k*m where m = len(word)
✓ Linear Space
Constraints
- 1 ≤ sequence.length ≤ 100
- 1 ≤ word.length ≤ 100
- sequence and word contain only lowercase English letters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code