You are given an integer array 'CARDS' of size 'N', where 'CARDS[i]' is the number written on the 'ith' card. You are also given an integer ‘GROUPSIZE’, where ‘GROUPSIZE’ is the size of each group.
These cards must be arranged in groups with consecutive numbers written on them.
We must return true if cards can be divided into groups and each card belongs to exactly one group. Else, return false.
Consider ‘N’ = 6, 'CARDS' = [1, 3, 2, 2, 4, 3] and ‘GROUPSIZE’ = 2.
Then, the first and third cards with numbers 1 and 2 can be in one group, the second and fourth cards with numbers 3 and 2 can be in one group and the fifth and the sixth cards with numbers 4 and 3 can be in one group.
Hence we return true.
The first line contains two integers ‘N’ and 'GROUPSIZE', representing the number of cards and the size of each group.
The second line will contains ‘N’ space-separated integers representing array ‘CARDS’.
Output Format :
Print 'true' if cards can be divided into groups. Else print 'false'.
Note :
You don’t need to print anything; It has already been handled. Just implement the given function.
1 1
1
true
There is only one card, and it belongs to one group.
6 2
2 1 3 3 2 2
true
1 <= N, GROUPSIZE <= 10^5
1 <= CARDS[i] <= N
Time limit: 1 sec
We can count the integer written on cards in a hash map.
Approach
Here is the algorithm :
O(N*LogN), where 'N' is the number of cards.
We sort the ‘CARDS’ array before iterating, which requires O(N*LogN) time. As we loop through each card once, the succeeding iterations need O(N) time.
Hence the overall time complexity will be O(N*LogN).
O(N), where 'N' is the number of cards.
Extra space is used by the hash map, to store the frequency of each element in ‘CARDS’ array.
Hence the overall time complexity will be O(N).