1668. Maximum Repeating Substring LeetCode Solution
In this guide, you will get 1668. Maximum Repeating Substring LeetCode Solution with the best time and space complexity. The solution to Maximum Repeating Substring problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Repeating Substring solution in C++
- Maximum Repeating Substring solution in Java
- Maximum Repeating Substring solution in Python
- Additional Resources
Problem Statement of Maximum Repeating Substring
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.
Example 1:
Input: sequence = “ababc”, word = “ab”
Output: 2
Explanation: “abab” is a substring in “ababc”.
Example 2:
Input: sequence = “ababc”, word = “ba”
Output: 1
Explanation: “ba” is a substring in “ababc”. “baba” is not a substring in “ababc”.
Example 3:
Input: sequence = “ababc”, word = “ac”
Output: 0
Explanation: “ac” is not a substring in “ababc”.
Constraints:
1 <= sequence.length <= 100
1 <= word.length <= 100
sequence and word contains only lowercase English letters.
Complexity Analysis
- Time Complexity: O(n^2)
- Space Complexity: O(n)
1668. Maximum Repeating Substring LeetCode Solution in C++
class Solution {
public:
int maxRepeating(string sequence, string word) {
int ans = 1;
string repeating = word;
while (sequence.find(repeating) != string::npos) {
++ans;
repeating += word;
}
return ans - 1;
}
};
/* code provided by PROGIEZ */
1668. Maximum Repeating Substring LeetCode Solution in Java
class Solution {
public int maxRepeating(String sequence, String word) {
int ans = 1;
while (sequence.contains(word.repeat(ans)))
++ans;
return ans - 1;
}
}
// code provided by PROGIEZ
1668. Maximum Repeating Substring LeetCode Solution in Python
class Solution:
def maxRepeating(self, sequence: str, word: str) -> int:
ans = 1
while word * ans in sequence:
ans += 1
return ans - 1
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.