Last Updated: 14 Sep, 2022

Split String

Easy
Asked in company
Google inc

Problem statement

You are given a string 'S'. A string is called a split string if it follows the conditions define below.

1. It can be divided into 'K' contiguous substrings such that the first letter of these substrings is the same for all the substrings.
2. It can be divided into 'K' contiguous substrings such that the first letter of these substrings is distinct for all the substrings.

Return 1 if 'S' is a split string otherwise return 0.

For Example:-
Let 'N' = 6, 'K' = 2, 'S' = "pppdpa".
It can be divided into "pp" and "pdpa", the first letter of the strings is same.
It can be divided into "ppp" and "dpa", the first letter of the strings is distinct.
So our answer is 1. 
Input Format:-
First-line contains an integer 'T', which denotes the number of test cases.
For every test case:-
First-line contains two integers 'N' and 'K'.
Second-line contains a String 'S', which consists of 'N' lowercase English letters.         
Output Format:-
For each test case, Return 1 if 'S' is a split string otherwise return 0.
Note:-
You don’t need to print anything. Just implement the given function.
Constraints:-
1 <= 'T' <= 10
1 <= 'N' <= 10^5
'S' consists of 'N' lowercase English letters.

The Sum of 'N' overall test cases does not exceed 10^5.
Time Limit: 1 sec

Approaches

01 Approach

Approach:-

 

  • For following the first Condition:
    • To make the first letter of the 'K' strings same, some letters must have their occurrence greater than or equal to 'K' in 'S'.
  • For following the second Condition:
    • To make the first letter of the 'K' strings distinct, there must be at least 'K' distinct letters in 'S'.
  • Iterate in 'S' and count the occurrence of the letters in the hashmap.
  • If the occurrence of any letter is greater than or equal to 'K' and the number of distinct letters in 'S' is greater than or equal to 'K', then our answer is 1 otherwise 0.
     

 Algorithm:-
 

  • Create a hashmap 'occ' of [char,int].
  • Initialize flag with 0.
  • Iterate using 'i' in 'S':
    • occ[S[i]]++.
    • if(occ[S[i]] >= 'K'):
      • flag=1;
  • If(flag==1 && occ.size() >= 'K'):
    • return 1.
  • else:
    • return 0.