You are given a string s
, and your task is to find the maximum length x
of a special substring that appears at least three times in s
.
A special substring is defined as a substring containing only one unique character (e.g., "aaa"
, "bbbb"
).
If no such substring exists, return -1
.
The problem exhibits a monotonic property:
x
exists at least three times, then all substrings of length < x
are also valid.x
is invalid, all x > x
are also invalid.Using binary search, we efficiently search for the largest possible x
:
l = 1
(minimum substring length) and r = n
(length of the string s
).x
is possible.To validate if a given x
is valid:
x
to traverse the string.true
if any substring occurs at least three times.x
.l
is valid after the search, return l
.-1
.Time Complexity:
O(log n)
iterations for a string of length n
.x
: O(n)
using sliding window.O(n log n)
.Space Complexity:
O(n)
for the hashmap used during validation.Input:
s = "aaabbbaaa"
Output:
3
Explanation:
"aaa"
occurs 3 times in the string.Input:
s = "abc"
Output:
-1
Explanation:
Input:
s = "aaaaaa"
Output:
6
Explanation:
"aaaaaa"
is the entire string and appears 3 times (as a whole).Input:
s = "abbbbbbbc"
Output:
5
Explanation:
"bbbbb"
appears at least 3 times in the string.Input:
s = "aabbcc"
Output:
-1
Explanation:
Single Character String: Input:
s = "a"
Output:
-1
Explanation: A single character cannot occur 3 times as a substring.
String with No Repeats: Input:
s = "abcdef"
Output:
-1
Explanation: No character repeats consecutively.
Already Valid Entire String: Input:
s = "ccc"
Output:
3
Explanation: The entire string forms a valid substring of length 3, occurring exactly 3 times.
Loading component...
Loading component...
Main Function is not defined.
public int maximumLength(String s){
int n = s.length();
int l = 1;
int r = n;
boolean boolean_value = helper(s, n,l);
if(!boolean_value){
return -1;
}
while(l+1 < r) {
int mid = (l+r) /2;
boolean_value = helper(s,n, mid);
if(boolean_value){
l =mid;
}
else{
r = mid;
}
}
return l;
}//function end
private boolean helper(String s, int n, int x){
int[] cnt = new int[26];
int p =0;
for(int i =0; i <n; i++){
while(s.charAt(p) != s.charAt(i)){
p++;
}
if( i -p +1 >= x ){
cnt[ s.charAt(i) - 'a' ]++;
}
if (cnt[s.charAt(i) - 'a' ] > 2){
return true;
}
}
return false;
}//function end