Similar Problems

Similar Problems not available

Maximum Repeating Substring - Leetcode Solution

Companies:

LeetCode:  Maximum Repeating Substring Leetcode Solution

Difficulty: Easy

Topics: string  

The Maximum Repeating Substring problem on LeetCode asks us to find the maximum number of times a given substring patterns occurs inside another string.

Example:

Input: str = "ababc", pattern = "ab" Output: 2

Explanation: The substring "ab" occurs twice in the string "ababc" - "ab" (at position 1) and "ab" (at position 3).

To solve this problem, we can use a simple iteration approach. We first create a variable 'count' to store the maximum number of times the pattern occurs in the string. We then iterate through the string with a nested loop. The outer loop moves the starting index of the substring, while the inner loop compares each character of the substring with the pattern. If there is a character mismatch, we break the inner loop and move on to the next substring. If all characters match, we increment the count and move on to the next substring.

Here's the detailed solution:

class Solution:
    def maxRepeating(self, sequence: str, word: str) -> int:
        
        count = 0
        n = len(sequence)
        m = len(word)
        
        # iterate through all possible starting indices of substring
        for i in range(n - m + 1):
            j = 0
            # iterate through each character of the substring
            while j < m and sequence[i+j] == word[j]:
                j += 1
            # if all characters match, increment count and move to next substring
            if j == m:
                count += 1
                j = 0
        
        return count

Time Complexity: O(n*m) where n is the length of the sequence and m is the length of the word.

Space Complexity: O(1) since we are not using any extra space except for a few variables.

Maximum Repeating Substring Solution Code

1