Maximum Repeating Substring
Given a string word and a string sequence, find the maximum number of times word appears consecutively in sequence. The word must appear back-to-back without gaps between repetitions.
For example, in sequence "ababc" with word "ab", the maximum consecutive repetitions is 2 ("abab" at the start). In "abababc" with "ab", it is 3. In "abc" with "ab", it is 1. If word does not appear at all, return 0.
This problem teaches substring matching with consecutive repetition counting. It is used in text compression (finding repeated patterns), DNA sequence analysis (finding repeated gene segments), and data deduplication.
The solution builds progressively longer repeated strings ("ab", "abab", "ababab") and checks if the built string is a substring of the sequence. The maximum k such that word repeated k times is found in the sequence is the answer.
Edge cases include an empty word or sequence (return 0), word longer than sequence (return 0 or 1 if word equals sequence), and no match at all (return 0).
Example Input & Output
'ab' repeats twice in 'ababc': 'ab' + 'ab' but only 'abab'=2
Empty string
'a' repeats 4 times: 'aaaa'
'ba' appears once
'ac' not found
Algorithm Flow
Solution Approach
Build repeated versions of the word and check if they exist in the sequence.
Initialize k to 0 and built to word. While the current built string is found within the sequence, increment k and append word again to built. When the built string is no longer found, return k, which represents the maximum consecutive repetitions.
Time complexity is O(n * k) where n is the sequence length and k is the repetition count. Space complexity is O(n) for the built string.
Best Answers
class Solution {
public int solution(String seq, String word) {
int k=0;String r=word;
while(seq.contains(r)){k++;r+=word;}
return k;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
