#1668

Maximum Repeating Substring

Easy
StringDynamic ProgrammingString MatchingString MatchingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of constructing new strings, we can count how many times the word appears consecutively in the sequence. This reduces unnecessary string operations and leads to a linear time solution.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize count to 0 and a variable to track the current position in the sequence.
  2. 2Step 2: While there are enough characters left in the sequence to match the word, check if the substring matches the word.
  3. 3Step 3: If it matches, increment count and move the position forward by the length of the word. Otherwise, break the loop.
  4. 4Step 4: Return count as the maximum k-repeating value.
solution.py11 lines
1def maxRepeating(sequence, word):
2    count = 0
3    word_length = len(word)
4    i = 0
5    while i + word_length <= len(sequence):
6        if sequence[i:i + word_length] == word:
7            count += 1
8            i += word_length
9        else:
10            break
11    return count

Complexity note: This complexity is linear because we traverse the sequence only once, checking for matches with the word without constructing new strings.

  • 1Understanding how to efficiently check for substrings can significantly reduce time complexity.
  • 2Recognizing when to use string operations versus counting can lead to optimal solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.