Given an array arr[] consisting of N integers, the task is to check if it is possible to split the integers into two equal length subsets such that all repetitions of any array element belong to the same subset. If found to be true, print “Yes”. Otherwise, print “No”.
Examples:
Input: arr[] = {2, 1, 2, 3}
Output: Yes
Explanation:
One possible way of dividing the array is {1, 3} and {2, 2}Input: arr[] = {1, 1, 1, 1}
Output: No
Naive Approach: The simplest approach to solve the problem is to try all possible combinations of splitting the array into two equal subsets. For each combination, check whether every repetition belongs to only one of the two sets or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Time Complexity: O(2N), where N is the size of the given integer.
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by storing the frequency of all elements of the given array in an array freq[]. For elements to be divided into two equal sets, N/2 elements must be present in each set. Therefore, to divide the given array arr[] into 2 equal parts, there must be some subset of integers in freq[] having sum N/2. Follow the steps below to solve the problem:
- Store the frequency of each element in Map M.
- Now, create an auxiliary array aux[] and insert it into it, all the frequencies stored from the Map.
- The given problem reduces to finding a subset in the array aux[] having a given sum N/2.
- If there exists any such subset in the above step, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Java
// Java program for the above approachimport java.io.*;import java.util.*;class GFG { // Function to create the frequency // array of the given array arr[] private static int[] findSubsets(int[] arr) { // Hashmap to store the frequencies HashMap<Integer, Integer> M = new HashMap<>(); // Store freq for each element for (int i = 0; i < arr.length; i++) { M.put(arr[i], M.getOrDefault(arr[i], 0) + 1); } // Get the total frequencies int[] subsets = new int[M.size()]; int i = 0; // Store frequencies in subset[] array for ( Map.Entry<Integer, Integer> playerEntry : M.entrySet()) { subsets[i++] = playerEntry.getValue(); } // Return frequency array return subsets; } // Function to check is sum N/2 can be // formed using some subset private static boolean subsetSum(int[] subsets, int target) { // dp[i][j] store the answer to // form sum j using 1st i elements boolean[][] dp = new boolean[subsets.length + 1][target + 1]; // Initialize dp[][] with true for (int i = 0; i < dp.length; i++) dp[i][0] = true; // Fill the subset table in the // bottom up manner for (int i = 1; i <= subsets.length; i++) { for (int j = 1; j <= target; j++) { dp[i][j] = dp[i - 1][j]; // If curren element is // less than j if (j >= subsets[i - 1]) { // Update current state dp[i][j] |= dp[i - 1][j - subsets[i - 1]]; } } } // Return the result return dp[subsets.length][target]; } // Function to check if the given // array can be split into required sets public static void divideInto2Subset(int[] arr) { // Store frequencies of arr[] int[] subsets = findSubsets(arr); // If size of arr[] is odd then // print "Yes" if ((arr.length) % 2 == 1) { System.out.println("No"); return; } // Check if answer is true or not boolean isPossible = subsetSum(subsets, arr.length / 2); // Print the result if (isPossible) { System.out.println("Yes"); } else { System.out.println("No"); } } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 2, 1, 2, 3 }; // Function Call divideInto2Subset(arr); }} |
Python3
# Python3 program for the # above approachfrom collections import defaultdict# Function to create the # frequency array of the # given array arr[]def findSubsets(arr): # Hashmap to store # the frequencies M = defaultdict (int) # Store freq for each element for i in range (len(arr)): M[arr[i]] += 1 # Get the total frequencies subsets = [0] * len(M) i = 0 # Store frequencies in # subset[] array for j in M: subsets[i] = M[j] i += 1 # Return frequency array return subsets# Function to check is # sum N/2 can be formed # using some subsetdef subsetSum(subsets, target): # dp[i][j] store the answer to # form sum j using 1st i elements dp = [[0 for x in range(target + 1)] for y in range(len(subsets) + 1)] # Initialize dp[][] with true for i in range(len(dp)): dp[i][0] = True # Fill the subset table in the # bottom up manner for i in range(1, len(subsets) + 1): for j in range(1, target + 1): dp[i][j] = dp[i - 1][j] # If current element is # less than j if (j >= subsets[i - 1]): # Update current state dp[i][j] |= (dp[i - 1][j - subsets[i - 1]]) # Return the result return dp[len(subsets)][target]# Function to check if the given# array can be split into required setsdef divideInto2Subset(arr): # Store frequencies of arr[] subsets = findSubsets(arr) # If size of arr[] is odd then # print "Yes" if (len(arr) % 2 == 1): print("No") return # Check if answer is true or not isPossible = subsetSum(subsets, len(arr) // 2) # Print the result if (isPossible): print("Yes") else : print("No")# Driver Codeif __name__ == "__main__": # Given array arr arr = [2, 1, 2, 3] # Function Call divideInto2Subset(arr)# This code is contributed by Chitranayal |
C#
// C# program for the above // approachusing System;using System.Collections.Generic; class GFG{ // Function to create the frequency// array of the given array arr[]static int[] findSubsets(int[] arr){ // Hashmap to store the // frequencies Dictionary<int, int> M = new Dictionary<int, int>(); // Store freq for each element for (int i = 0; i < arr.Length; i++) { if(M.ContainsKey(arr[i])) { M[arr[i]]++; } else { M[arr[i]] = 1; } } // Get the total frequencies int[] subsets = new int[M.Count]; int I = 0; // Store frequencies in // subset[] array foreach(KeyValuePair<int, int> playerEntry in M) { subsets[I] = playerEntry.Value; I++; } // Return frequency array return subsets;}// Function to check is sum // N/2 can be formed using // some subsetstatic bool subsetSum(int[] subsets, int target){ // dp[i][j] store the answer to // form sum j using 1st i elements bool[,] dp = new bool[subsets.Length + 1, target + 1]; // Initialize dp[][] with true for (int i = 0; i < dp.GetLength(0); i++) dp[i, 0] = true; // Fill the subset table in the // bottom up manner for (int i = 1; i <= subsets.Length; i++) { for (int j = 1; j <= target; j++) { dp[i, j] = dp[i - 1, j]; // If curren element is // less than j if (j >= subsets[i - 1]) { // Update current state dp[i, j] |= dp[i - 1, j - subsets[i - 1]]; } } } // Return the result return dp[subsets.Length, target];}// Function to check if the given// array can be split into required setsstatic void divideInto2Subset(int[] arr){ // Store frequencies of arr[] int[] subsets = findSubsets(arr); // If size of arr[] is odd then // print "Yes" if ((arr.Length) % 2 == 1) { Console.WriteLine("No"); return; } // Check if answer is true or not bool isPossible = subsetSum(subsets, arr.Length / 2); // Print the result if (isPossible) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); }} // Driver codestatic void Main() { // Given array arr[] int[] arr = {2, 1, 2, 3}; // Function Call divideInto2Subset(arr);}}// This code is contributed by divyeshrabadiya07 |
Yes
Time Complexity: O(N*M), where N is the size of the array and M is the total count of distinct elements in the given array.
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Split array into maximum subarrays such that every distinct element lies in a single subarray
- Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
- Partition array into minimum number of equal length subsets consisting of a single distinct value
- Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
- Partition a set into two non-empty subsets such that the difference of subset sums is maximum
- Partition a set into two subsets such that the difference of subset sums is minimum
- Split numbers from 1 to N into two equal sum subsets
- Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
- Split N powers of 2 into two subsets such that their difference of sum is minimum
- Divide array in two Subsets such that sum of square of sum of both subsets is maximum
- Split Array into min number of subsets with difference between each pair greater than 1
- Split array into minimum number of subsets having maximum pair sum at most K
- Check if it is possible to split given Array into K odd-sum subsets
- Split array into K subsets to maximize their sum of maximums and minimums
- Check if an array can be split into subsets of K consecutive elements
- Largest possible Subset from an Array such that no element is K times any other element in the Subset
- Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
- Maximum sum of Bitwise XOR of all elements of two equal length subsets
- Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
- Sum of subsets of all the subsets of an array | O(3^N)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

