Q: Find the longest substring that contains at least one character who's frequency is greater than or equal to the (length of that substring)/2..
constraint:
1<=n<=105 (length of string inputted)
input:
2
5
abcde
14
ababbbacbcbcca
output:
3
13
Sample test case 2: We can select the substring starting from index 1 to 13, here the frequency of b is 6 which is greater than or equal to 13/2=6.
Note that, there can be multiple possible substrings.
My approach:
I already tried the brute force method, but that is not very efficient way of dealing with this problem.. Any hints on how to deal with this, here's the brute force way
#include <iostream>
#include <cmath>
#include <algorithm>
#include <limits>
#include <vector>
#include <bitset>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <time.h>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <cctype>
#include <list>
#include <iterator>
#include <iosfwd>
using std::cin;
using std::cout;
int main() {
int t;cin>>t;while(t--){ //test cases
int n;cin>>n; //length of string
string s;cin>>s; //string input
int max_sub=-1; //result
for(int i=0;i<n;i++)
{
for(int len=1;len<=n-i;len++)
{
string s1=s.substr(i,len); //get all the sub strings(hence brute force)
//cout<<s1<<"\n";
map<char,int> m; //map to find the frequencies
for(int j=0;j<s1.length();j++) //take the substring
{
m[s1[j]]++;//count the frequency
int val=s1.length();
if(m[s1[j]]>=val/2) // if found any character with freq >= (length of substring)/2
{
if(val>max_sub) //check if length is greater than prev max value
{max_sub=val;} //update
break;//break, since we need atleast one character(so only one chacter will do the job)
}
}
}
}
cout<<max_sub<<"\n"; //print the result
}
return 0;
}
This problem doesn't seem well-defined. How can the answer to problem 2 be the substring from 1 to 13? That's 13 characters long but b's freq is only 6. Why are they dividing 13 by 2? The description doesn't mention dividing by 2.
If the source of these problems is a secret, then I won't help anymore. :(
If not, post the link.