PROBLEM LINK:
Author & Editorialist: Daanish Mahajan
Testers: Shubham Jain, Aryan Choudhary
DIFFICULTY:
Simple
PREREQUISITES:
Running Sum
PROBLEM:
Given a string S of length N and an integer K, tell whether there exists a substring of length K having each character as '*'.
EXPLANATION:
Subtask 1: We can manually check all the possible N - K + 1 substrings of length K in \mathcal{O}(K * (N - K)) per test case.
Subtask 2: Assume the string starts with x_1 consecutive characters from the set [a, z] followed by x_2 consecutive characters '*' followed by x_3 consecutive characters from the set [a, z] and so on. So answer = max(x_{2i}) where i >= 1.
The values of x_i can be calculated linearly by comparing the present character with the previous character and incrementing the counter if they are the same or pushing the value of the counter in the vector and setting it to one if not. But it requires \mathcal{O}(N) extra space.
To avoid using vector, increment the counter only when the present character is a '*', else keep the value of counter as 0 and take the maximum value of the counter at each iteration as the answer.
So the final time complexity is \mathcal{O}(N) per test case.
SOLUTIONS:
Setter's Solution
#include<bits/stdc++.h>
using namespace std;
const int maxt = 10, maxl = 1e6;
int main()
{
int t; cin >> t;
int tn = 0;
while(t--){
int n, k; cin >> n >> k; tn += n;
string s; cin >> s;
for(char c : s){
assert((c >= 'a' && c <= 'z') || c == '*');
}
int maxv = 0, cnt = 0;
// for(int i = 0; i <= n - k && maxv < k; i++){
// if(s[i] != '*')continue;
// int cnt = 0;
// for(int j = i; j <= i + k - 1; j++){
// if(s[j] != '*')break;
// cnt++;
// }
// maxv = max(maxv, cnt);
// }
for(char c : s){
if(c == '*')cnt++;
else{
maxv = max(maxv, cnt); cnt = 0;
}
}
maxv = max(maxv, cnt);
string ans = maxv >= k ? "YeS" : "No";
cout << ans << endl;
}
assert(tn <= maxl);
}
Tester's Solution
#include<bits/stdc++.h>
using namespace std;
const long long int mod = 1000000007L;
long long int T,n,i,j,k,in,cnt,l,r,u,v,x,y;
long long int m;
string s;
int main(void) {
ios_base::sync_with_stdio(false);cin.tie(NULL);
cin >> T;
while(T--)
{
cin >> n >> k >> s;
long long int mx=0,cnt=0;
for(auto x:s)
{
assert(('a'<=x&&x<='z')||(x=='*'));
if(x=='*')
cnt++;
else
cnt=0;
mx=max(mx,cnt);
}
cout<<(mx>=k?"YeS":"nO")<<endl;
}
return 0;
}