Maximum Repeating Substring - Problem

For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence.

If word is not a substring of sequence, word's maximum k-repeating value is 0.

Given strings sequence and word, return the maximum k-repeating value of word in sequence.

Input & Output

Example 1 — Basic Repeating Pattern
$ Input: sequence = "ababc", word = "ab"
Output: 2
💡 Note: "ab" appears once, "abab" (ab repeated 2 times) appears as substring in "ababc", but "ababab" (3 times) does not. Maximum k-repeating value is 2.
Example 2 — No Repetition
$ Input: sequence = "ababc", word = "ba"
Output: 1
💡 Note: "ba" appears once in "ababc", but "baba" (repeated 2 times) does not appear. Maximum k-repeating value is 1.
Example 3 — Word Not Found
$ Input: sequence = "ababc", word = "ac"
Output: 0
💡 Note: "ac" does not appear as substring in "ababc". Maximum k-repeating value is 0.

Constraints

  • 1 ≤ sequence.length ≤ 100
  • 1 ≤ word.length ≤ 100
  • sequence and word consists of lowercase English letters.

Visualization

Tap to expand
Maximum Repeating Substring INPUT sequence = "ababc" a b a b c 0 1 2 3 4 word = "ab" a b Find "ab" repeated in sequence: "abab" "ab" x 2 = "abab" found! "ab" x 3 = "ababab" NOT found ALGORITHM STEPS 1 Initialize k = 1, maxK = 0 pattern = word = "ab" 2 Check k=1 "ab" in "ababc"? Yes maxK = 1, pattern = "abab" 3 Check k=2 "abab" in "ababc"? Yes maxK = 2, pattern = "ababab" 4 Check k=3 "ababab" in "ababc"? No Stop loop, return maxK k pattern found 1 ab OK 2 abab OK 3 ababab NO FINAL RESULT Maximum k-repeating value: 2 The word "ab" can be repeated 2 times to form "abab" which exists in "ababc" Verification: "ab" x 2 = "abab" Found at position 0: a b a b c Key Insight: The optimized single-pass approach incrementally builds the repeated pattern by concatenating the word to itself. We check if each longer pattern exists in the sequence, stopping when it doesn't. This avoids recalculating from scratch, achieving O(n*m) time where n = sequence length. TutorialsPoint - Maximum Repeating Substring | Optimized Single Pass
Asked in
Google 15 Microsoft 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen