Substring Problem

closed account (N3wCDjzh)
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#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;
}


src: https://www.hackerearth.com/challenge/competitive/december-circuits-18/algorithm/superior-substring-dec-circuits-e51b3c27/
Last edited on
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.
closed account (N3wCDjzh)
sorry, my bad I forgot to mention (length of string)/2 and src is provided in the edited version..:)
closed account (N3wCDjzh)
any hints you could give for this one ??
closed account (N3wCDjzh)
@dutch ??
Topic archived. No new replies allowed.