Leetcode 1668. Maximum Repeating Substring
We are given a string sequence
and a string word
. We need to determine the maximum integer k
such that word
repeated k
times is a substring of sequence
.
What is the maximum length of sequence
and word
?
Typically, constraints will mention these values. Let’s assume sequence
can be very large, up to 1000 characters, while word
can be up to 100 characters.
Can sequence
or word
contain special characters or whitespace?
Assume both can consist of any printable characters, including lowercase and uppercase letters, digits, punctuation, and whitespace.
Is k
guaranteed to be at least 1?
Yes, the problem implies finding the maximum repeating k
, where k
is at least 1.
To solve this problem, we need to form the repeated versions of word
and check whether it is a substring of sequence
.
k
to 0 - a variable to keep track of the maximum repeats.word
k
times.k=1
to the point where the repeated string cannot be found in sequence
.Steps:
k=1
and repeatedly append word
to itself.sequence
.k
and repeat.sequence
.k
is the answer.Here’s the implementation in Java:
public class MaximumRepeatingSubstring {
public int maxRepeating(String sequence, String word) {
int k = 0;
String repeatedWord = word;
// Try increasing k by checking repeating word["", "word", "wordword", ...] in sequence
while (sequence.contains(repeatedWord)) {
k++;
repeatedWord += word;
}
return k;
}
public static void main(String[] args) {
MaximumRepeatingSubstring mrs = new MaximumRepeatingSubstring();
// Example tests
System.out.println(mrs.maxRepeating("ababc", "ab")); // Output: 2
System.out.println(mrs.maxRepeating("ababc", "ba")); // Output: 1
System.out.println(mrs.maxRepeating("ababc", "ac")); // Output: 0
}
}
word
.k*m
(where m
is length of word
) is a substring of sequence
(length n
) can be done in O(n) time in the worst case.Since these operations are performed up to k
times:
Therefore, the overall time complexity is O(k * (m + n)). In the worst case, k could be approximately n / m.
This ensures an efficient and clear solution for the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?