Code Logo

Maximum Repeating Substring

Published at25 Jul 2026
Medium 1 views
Like0

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

Example 1
Input
"ababc","ab"
Output
2
Explanation

'ab' repeats twice in 'ababc': 'ab' + 'ab' but only 'abab'=2

Example 2
Input
"","a"
Output
0
Explanation

Empty string

Example 3
Input
"aaaa","a"
Output
4
Explanation

'a' repeats 4 times: 'aaaa'

Example 4
Input
"ababc","ba"
Output
1
Explanation

'ba' appears once

Example 5
Input
"ababc","ac"
Output
0
Explanation

'ac' not found

Algorithm Flow

Recommendation Algorithm Flow for Maximum Repeating Substring

Solution Approach

Build repeated versions of the word and check if they exist in the sequence.

function maxRepeating(sequence, word)
  var k = 0, built = word
  while sequence.indexOf(built) !== -1
    k = k + 1
    built = built + word
  return k

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

java
class Solution {
    public int solution(String seq, String word) {
        int k=0;String r=word;
        while(seq.contains(r)){k++;r+=word;}
        return k;
    }
}