Given an array, 'ARR' of 'N' integers print “true” if it is possible to split the array into some finite number of subsets such that each subset has the same integer in it and all subsets have the same size. The size of the subset should be greater than one.
Print “false” if it is not possible to do the above task.
Example:Input: 'ARR' = [1, 2, 4, 4, 1, 2]
Output: true
We can split the above array like this: [1, 1], [4, 4], [2, 2]
In the three subsets, each of size two. And every subset contains the same elements.
The first line of input contains an integer 'T', denoting the number of test cases.
The first line of each test case contains a single integer 'N' size of the input array ‘ARR’. The second line contains 'N' integers the array elements.
Output format :
For each test case, print "true" if it is possible to split the array else print "false".
Output for each test case will be printed in a separate line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
1 <= 'N' <= 10^5
-10^9 <= 'ARR[i]'<= 10^9
Time Limit : 1 sec
2
6
2 2 4 5 4 5
5
4 3 5 6 3
true
false
For the first test case, we can split the array like this: [2, 2], [4, 4], [5, 5].
For the second test case, it is not possible to split the array with the given condition.
2
6
2 3 4 5 3 5
9
2 3 3 2 3 1 2 1 1
false
true
Try to think of counting the frequency of every number in the array.
Approach:
We can easily solve this problem by counting the frequency of every number of the array using a hashmap, and then we can form the groups according to the gcd of frequency count.
If the gcd is one then it is not possible to split the array, else it is possible.
Algorithm:
O(N * Log(N) * Log(N)), where 'N' is the length of the input array 'ARR'.
Since we are using hashmap for every key insertion and updation, it will take Log(N) complexity. Also, simultaneously we are looping over the whole array of size 'N' and calculating the gcd, the gcd operation will take another Log(N) time; hence the overall time complexity will be O(N * Log(N) * Log(N)).
O(N), where 'N' is the length of the input array 'ARR'.
In the worst-case Map can contain 'N' key-value pairs. Hence the overall space complexity will be O(N).