Skip to content
Related Articles

Related Articles

Check if Array can be divided into K groups of size C and all elements of group are distinct

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 17 Oct, 2022
Improve Article
Save Article

Given an array A[] of size N, and two integers K and C, the task is to check if all the elements of the array can be grouped into K groups such that each group has at most C elements and all the elements of a group are distinct.

Examples:

Input: N=6, A=[1, 2, 1, 2, 3, 4], K = 2, C=3
Output: Possible
Explanation: Let 2 groups be k1, k2 of capacity 3.
If we put element with positive integer 1, 2, 3 on group k1 i.e k1 have [1, 2, 3] and 
if we put remaining 3 elements 1, 2, 4 on group k2 i.e k2 have [1, 2, 4] then it possible
to put all the balls .

Input: N = 8, Balls = [1, 1, 1, 1, 1, 2, 2, 2], K = 2, C = 4
Output: Impossible
Explanation: It is not possible to put the elements into
2 groups such that each group has all unique elements

 Approach: The problem can be solved based on the following idea:

Store the frequency count of each element. If any element has frequency count of more than K then the answer cannot exist.

Follow the steps mentioned below to implement the idea.

  • Declare a map.
  • Store the frequency of every element inside the map.
  • Iterate over the map and check if any element has a frequency greater than K then print the impossible and return.
  • Check if N > K*C then print Impossible and return.
  • Otherwise, the answer is possible.

Below is the Implementation of the approach 

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function Performing Calculation
bool Check(int N, vector<int>& Balls, int K, int C)
{
    // Declaring a map
    map<int, int> freq;
    for (auto i : Balls)
 
        // Storing the frequencies of every element
        freq[i]++;
 
    for (auto i : freq) {
 
        // Checking the first
        if (i.second > K) {
            return false;
        }
    }
 
    // Checking if number of element present exceed the
    // capacity.
    if (N > K * C)
        return false;
    return true;
}
 
// Driver code
int main()
{
    int N = 8;
    vector<int> Balls = { 1, 1, 1, 1, 1, 2, 2, 2 };
 
    int K = 2;
    int C = 4;
 
    // Function call
    if (Check(N, Balls, K, C)) {
        cout << "Possible" << endl;
    }
    else {
        cout << "Impossible" << endl;
    }
    return 0;
}


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function performing calculation
    static boolean Check(int N, int[] Balls, int K, int C)
    {
        // Declaring a map
        HashMap<Integer, Integer> freq = new HashMap<>();
        for (int i = 0; i < Balls.length; i++) {
            // Storing the frequencies of every element
            freq.put(Balls[i],
                     freq.getOrDefault(Balls[i], 0) + 1);
        }
 
        for (int i : freq.values()) {
            // Checking the first
            if (i > K) {
                return false;
            }
        }
 
        // Checking if number of element present exceed the
        // capacity.
        if (N > K * C) {
            return false;
        }
        return true;
    }
 
    public static void main(String[] args)
    {
        int N = 8;
        int[] Balls = { 1, 1, 1, 1, 1, 2, 2, 2 };
 
        int K = 2;
        int C = 4;
 
        // Function call
        if (Check(N, Balls, K, C)) {
            System.out.print("Possible");
        }
        else {
            System.out.print("Impossible");
        }
    }
}
 
// This code is contributed by lokesh.


Python3




# Python code to implement the approach
 
# Function Performing Calculation
def Check(N,Balls,K,C)->bool:
   
    # Declaring a map
    freq = {}
    for i in Balls:
        if(i in freq):
           
            # Storing the frequencies of every element
            freq[i] += 1
        else:
            freq[i] = 1
    for i in freq:
        # Checking the first
        if(freq[i] > K):
            return False
    # Checking if number of element present exceed the capacity.
    if(N > (K*C)):
        return False
    return True
         
# Driver code
if __name__ == "__main__":
    N = 8
    Balls = [1,1,1,1,1,2,2,2]
    K = 2
    C = 4
 
    # Function call
    if(Check(N,Balls,K,C)):
        print("Possible")
    else:
        print("Impossible")
         
        # This code is contributed by ajaymakavana.


C#




// C# implementation of program
using System;
using System.Collections.Generic;
 
public class GFG
{
  // Function performing calculation
  static bool Check(int N, int[] Balls, int K, int C)
  {
     
    // Declaring a map
    Dictionary<int, int> freq = new Dictionary<int, int>();
    for (int i = 0; i < N; i++)
    {
       
      // Storing the frequencies of every element
      if (freq.ContainsKey(Balls[i])) {
        freq[Balls[i]]++;
      }
      else {
        freq.Add(Balls[i], 1);
      }
    }
 
    foreach (KeyValuePair<int, int> i in freq)
    {
       
      // Checking the first
      if (i.Value > K) {
        return false;
      }
    }
 
    // Checking if number of element present exceed the capacity.
    if (N > K * C) {
      return false;
    }
    return true;
  }
 
  public static void Main(string[] args)
  {
    int N = 8;
    int[] Balls = { 1, 1, 1, 1, 1, 2, 2, 2 };
 
    int K = 2;
    int C = 4;
 
    // Function call
    if (Check(N, Balls, K, C)) {
      Console.WriteLine("Possible");
    }
    else {
      Console.WriteLine("Impossible");
    }
  }
}
 
// This code is contributed by ajaymakavana.


Javascript




// JavaScript code to implement the approach
 
// Function Performing Calculation
function Check(N, Balls, K, C)
{
 
    // Declaring a map
    var freq = new Map()
    let count1 = 0;
    let count2 = 0;
     
    freq.set(Balls[0],++count1);
    freq.set(Balls[1],++count1);
    freq.set(Balls[2],++count1);
    freq.set(Balls[3],++count1);
    freq.set(Balls[4],++count1);
    freq.set(Balls[5],++count2);
    freq.set(Balls[6],++count2);
    freq.set(Balls[7],++count2);
 
    for (let i = 1; i = freq.size; i++) {
 
        // Checking the first
        if (freq.get(i)> K) {
            return false;
        }
    }
 
    // Checking if number of element present exceed the
    // capacity.
    if (N > K * C)
        return false;
    return true;
}
 
// Driver code
N = 8;
let Balls = [1, 1, 1, 1, 1, 2, 2, 2];
 
K = 2;
C = 4;
 
// Function call
if (Check(N, Balls, K, C)) {
    console.log("Possible");
}
else {
    console.log("Impossible");
}
 
var mp = new Map();
for(var i = 0; i < 10; i++){
    mp.set(i, i*5);
}
mp.set(6,mp.get(6)*10)
console.log(mp.values([0]));
 
// This code is contributed by adityamaharshi21.


Output

Impossible

Time Complexity: O(N log (N))
Auxiliary Space: O(N)

Space Optimized Approach:

The space requirement of the problem can be reduced. The array can be sorted so the frequency of each element can be counted without the usage of extra map because they will all be present in consecutive indices.

Follow the steps mentioned below to implement the idea:

  • Sort the array in ascending order.
  • Maintain a Count variable that will count the frequency of the present element.
  • If the frequency of any element is greater than K, Print “Impossible” and return;
  • Check if N > K*C then print Impossible and return.
  • Otherwise, an answer is possible.

Below is the implementation of the above approach

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function Performing Calculation
bool Check(int N, vector<int>& Balls, int K, int C)
{
    // Sorting the array using stl.
    sort(Balls.begin(), Balls.end());
 
    // Maintaining the count variable.
    int cnt = 1;
    for (int i = 0; i < N - 1; i++) {
        if (Balls[i] != Balls[i - 1]) {
            if (cnt > K)
                return false;
            cnt = 1;
        }
        else
            // Incrementing if the element is
            // same as previous
            cnt++;
    }
    // Checking if number of element present
    // Exceed the capacity.
    if (N > K * C)
        return false;
    return true;
}
 
// Driver code
int main()
{
    int N = 8;
    vector<int> Balls = { 1, 1, 1, 1, 1, 2, 2, 2 };
 
    int K = 2;
    int C = 4;
 
    // Function call
    if (Check(N, Balls, K, C)) {
        cout << "Possible" << endl;
    }
    else {
        cout << "Impossible" << endl;
    }
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
import java.util.*;
 
class GFG {
    // Function Performing Calculation
    public static boolean Check(int N, int Balls[], int K,
                                int C)
    {
        // Sorting the array.
        Arrays.sort(Balls);
 
        // Maintaining the count variable.
        int cnt = 1;
        for (int i = 1; i < N; i++) {
            if (Balls[i] != Balls[i - 1]) {
                if (cnt > K)
                    return false;
                cnt = 1;
            }
            else
                // Incrementing if the element is
                // same as previous
                cnt++;
        }
        // Checking if number of element present
        // Exceed the capacity.
        if (N > K * C)
            return false;
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 8;
        int Balls[] = { 1, 1, 1, 1, 1, 2, 2, 2 };
 
        int K = 2;
        int C = 4;
 
        // Function call
        if (Check(N, Balls, K, C) == true) {
            System.out.println("Possible");
        }
        else {
            System.out.println("Impossible");
        }
    }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Function Performing Calculation
def Check(N, Balls, K, C):
 
    # Sorting the array using stl.
    Balls.sort()
 
    # Maintaining the count variable.
    cnt = 1
 
    for i in range(0,N-1):   
        if ((Balls[i]) != (Balls[i - 1])):
            if (cnt > K):
                return False
            cnt = 1
        else:
            # Incrementing if the element is
            # same as previous
            cnt += 1
             
    # Checking if number of element present
    # Exceed the capacity.
    if (N > (K * C)):
        return False
    return True
 
# Driver code
N = 8
Balls = [ 1, 1, 1, 1, 1, 2, 2, 2 ]
 
K = 2
C = 4
 
# Function call
if (Check(N, Balls, K, C) is True):
    print("Possible")
 
else:
    print("Impossible")
   
  # This code is contributed by ksam24000


C#




// C# code to implement the approach
using System;
 
class GFG
{
 
  // Function Performing Calculation
  public static bool Check(int N, int[] Balls, int K,
                           int C)
  {
     
    // Sorting the array.
    Array.Sort(Balls);
 
    // Maintaining the count variable.
    int cnt = 1;
    for (int i = 1; i < N; i++) {
      if (Balls[i] != Balls[i - 1]) {
        if (cnt > K)
          return false;
        cnt = 1;
      }
      else
        // Incrementing if the element is
        // same as previous
        cnt++;
    }
    // Checking if number of element present
    // Exceed the capacity.
    if (N > K * C)
      return false;
    return true;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 8;
    int[] Balls = { 1, 1, 1, 1, 1, 2, 2, 2 };
 
    int K = 2;
    int C = 4;
 
    // Function call
    if (Check(N, Balls, K, C) == true) {
      Console.Write("Possible");
    }
    else {
      Console.Write("Impossible");
    }
  }
}
 
// This code is contributed by code_hunt.


Javascript




<script>
 
// Function Performing Calculation
function Check(N, Balls, K, C)
{
    // Sorting the array using stl.
    Balls.sort();
     
    // Maintaining the count variable.
    let cnt = 1;
    for (let i = 0; i < N - 1; i++) {
        if (Balls[i] != Balls[i - 1]) {
            if (cnt > K)
                return false;
            cnt = 1;
        }
        else
            // Incrementing if the element is
            // same as previous
            cnt++;
    }
    // Checking if number of element present
    // Exceed the capacity.
    if (N > K * C)
        return false;
    return true;
}
 
let N = 8;
let Balls = [ 1, 1, 1, 1, 1, 2, 2, 2 ];
 
let K = 2;
let C = 4;
 
// Function call
if (Check(N, Balls, K, C)) {
    console.log("Possible");
}
else {
    console.log("Impossible");
}
 
// This code is contributed by akashish__
 
</script>


Output

Impossible

Time Complexity: O(N * logN) the time taken for sorting is O(N * logN)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!