Code Logo

Maximum Repeating Substring

Published at25 Jul 2026
Medium 0 views
Like0

For a string sequence and a string word, return the maximum k such that word is a substring of sequence repeated k times. In other words, find the largest value of k where word repeated k times (word + word + ... + word, k times) is a substring of sequence.

Build word repeated k times for increasing k, checking if it's a substring of sequence. Stop when the repeated word is no longer found. The maximum k is the answer.

Time complexity is O(k * n) where k is the answer and n is the sequence length. Space is O(k * word.length) for building the repeated word.

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
Recommendation Algorithm Flow for Maximum Repeating Substring

Solution Approach

function solution(sequence, word) {
  var k = 0;
  var repeated = word;
  while (sequence.indexOf(repeated) !== -1) {
    k++;
    repeated += word;
  }
  return k;
}

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;
    }
}