Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
Last Updated :
12 Jul, 2025
Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first subset is minimum. If there is still a tie then print the partitions where the first subset is lexicographically smallest.
Examples:
Input : vec[] = {1, 7, 15, 29, 11, 9}
Output : [9, 15] [1, 7, 11, 29]
Explanation : Average of the both the subsets is 12
Input : vec[] = {1, 2, 3, 4, 5, 6}
Output : [1, 6] [2, 3, 4, 5].
Explanation : Another possible solution is [3, 4] [1, 2, 5, 6],
but print the solution whose first subset is lexicographically
smallest.
Observation :
If we directly compute the average of a certain subset and compare it with another subset's average, due to precision issues with compilers, unexpected results will occur. For example, 5/3 = 1.66666.. and 166/100 = 1.66. Some compilers might treat them as same, whereas some others won't.
Let the sum of two subsets under consideration be sub1 and sub2, and let their sizes be s1 and s2. If their averages are equal, sub1/s1 = sub2/s2 . Which means sub1*s2 = sub2*s1.
Also total sum of the above two subsets = sub1+sub2, and s2= total size - s1.
On simplifying the above, we get
(sub1/s1) = (sub1+sub2)/ (s1+s2) = (total sum) / (total size).
Now this problem reduces to the fact that if we can select a particular size
of subset whose sum is equal to the current subset's sum, we are done.
Approach :
Let us define the function partition(ind, curr_sum, curr_size), which returns true if it is possible to construct subset using elements with index equals to ind and having size equals to curr_size and sum equals to curr_sum.
This recursive relation can be defined as:
partition(ind, curr_sum, curr_size) = partition(ind+1, curr_sum, curr_size) || partition(ind+1, curr_sum - val[ind], curr_size-1).
Two parts on the right side of the above equations represent whether we including the element at index ind or not.
This is a deviation from the classic subset sum problem, in which subproblems are being evaluated again and again. Therefore we memorize the subproblems and turn it into a Dynamic Programming solution.
C++14
// C++ program to Partition an array of
// non-negative integers into two subsets
// such that average of both the subsets are equal
#include <bits/stdc++.h>
using namespace std;
vector<vector<vector<bool> > > dp;
vector<int> res;
vector<int> original;
int total_size;
// Function that returns true if it is possible to
// use elements with index = ind to construct a set of s
// ize = curr_size whose sum is curr_sum.
bool possible(int index, int curr_sum, int curr_size)
{
// base cases
if (curr_size == 0)
return (curr_sum == 0);
if (index >= total_size)
return false;
// Which means curr_sum cant be found for curr_size
if (dp[index][curr_sum][curr_size] == false)
return false;
if (curr_sum >= original[index]) {
res.push_back(original[index]);
// Checks if taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum -
original[index],
curr_size - 1))
return true;
res.pop_back();
}
// Checks if not taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum, curr_size))
return true;
// If no solution has been found
return dp[index][curr_sum][curr_size] = false;
}
// Function to find two Partitions having equal average
vector<vector<int> > partition(vector<int>& Vec)
{
// Sort the vector
sort(Vec.begin(), Vec.end());
original.clear();
original = Vec;
dp.clear();
res.clear();
int total_sum = 0;
total_size = Vec.size();
for (int i = 0; i < total_size; ++i)
total_sum += Vec[i];
// building the memoization table
dp.resize(original.size(), vector<vector<bool> >
(total_sum + 1, vector<bool>(total_size, true)));
for (int i = 1; i < total_size; i++) {
// Sum_of_Set1 has to be an integer
if ((total_sum * i) % total_size != 0)
continue;
int Sum_of_Set1 = (total_sum * i) / total_size;
// We build our solution vector if its possible
// to find subsets that match our criteria
// using a recursive function
if (possible(0, Sum_of_Set1, i)) {
// Find out the elements in Vec, not in
// res and return the result.
int ptr1 = 0, ptr2 = 0;
vector<int> res1 = res;
vector<int> res2;
while (ptr1 < Vec.size() || ptr2 < res.size())
{
if (ptr2 < res.size() &&
res[ptr2] == Vec[ptr1])
{
ptr1++;
ptr2++;
continue;
}
res2.push_back(Vec[ptr1]);
ptr1++;
}
vector<vector<int> > ans;
ans.push_back(res1);
ans.push_back(res2);
return ans;
}
}
// If we havent found any such subset.
vector<vector<int> > ans;
return ans;
}
// Function to print partitions
void Print_Partition(vector<vector<int> > sol)
{
// Print two partitions
for (int i = 0; i < sol.size(); i++) {
cout << "[";
for (int j = 0; j < sol[i].size(); j++) {
cout << sol[i][j];
if (j != sol[i].size() - 1)
cout << " ";
}
cout << "] ";
}
}
// Driver code
int main()
{
vector<int> Vec = { 1, 7, 15, 29, 11, 9 };
vector<vector<int> > sol = partition(Vec);
// If partition possible
if (sol.size())
Print_Partition(sol);
else
cout << -1;
return 0;
}
Java
// Java program to Partition an array of
// non-negative integers into two subsets
// such that average of both the subsets are equal
import java.io.*;
import java.util.*;
class GFG
{
static boolean[][][] dp;
static Vector<Integer> res = new Vector<>();
static int[] original;
static int total_size;
// Function that returns true if it is possible to
// use elements with index = ind to construct a set of s
// ize = curr_size whose sum is curr_sum.
static boolean possible(int index, int curr_sum,
int curr_size)
{
// base cases
if (curr_size == 0)
return (curr_sum == 0);
if (index >= total_size)
return false;
// Which means curr_sum cant be found for curr_size
if (dp[index][curr_sum][curr_size] == false)
return false;
if (curr_sum >= original[index])
{
res.add(original[index]);
// Checks if taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum - original[index],
curr_size - 1))
return true;
res.remove(res.size() - 1);
}
// Checks if not taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum, curr_size))
return true;
// If no solution has been found
return dp[index][curr_sum][curr_size] = false;
}
// Function to find two Partitions having equal average
static Vector<Vector<Integer>> partition(int[] Vec)
{
// Sort the vector
Arrays.sort(Vec);
original = Vec;
res.clear();
int total_sum = 0;
total_size = Vec.length;
for (int i = 0; i < total_size; ++i)
total_sum += Vec[i];
// building the memoization table
dp = new boolean[original.length][total_sum + 1][total_size];
for (int i = 0; i < original.length; i++)
for (int j = 0; j < total_sum + 1; j++)
for (int k = 0; k < total_size; k++)
dp[i][j][k] = true;
for (int i = 1; i < total_size; i++)
{
// Sum_of_Set1 has to be an integer
if ((total_sum * i) % total_size != 0)
continue;
int Sum_of_Set1 = (total_sum * i) / total_size;
// We build our solution vector if its possible
// to find subsets that match our criteria
// using a recursive function
if (possible(0, Sum_of_Set1, i))
{
// Find out the elements in Vec, not in
// res and return the result.
int ptr1 = 0, ptr2 = 0;
Vector<Integer> res1 = res;
Vector<Integer> res2 = new Vector<>();
while (ptr1 < Vec.length || ptr2 < res.size())
{
if (ptr2 < res.size() &&
res.elementAt(ptr2) == Vec[ptr1])
{
ptr1++;
ptr2++;
continue;
}
res2.add(Vec[ptr1]);
ptr1++;
}
Vector<Vector<Integer>> ans = new Vector<>();
ans.add(res1);
ans.add(res2);
return ans;
}
}
// If we havent found any such subset.
Vector<Vector<Integer>> ans = new Vector<>();
return ans;
}
// Function to print partitions
static void Print_Partition(Vector<Vector<Integer>> sol)
{
// Print two partitions
for (int i = 0; i < sol.size(); i++)
{
System.out.print("[");
for (int j = 0; j < sol.elementAt(i).size(); j++)
{
System.out.print(sol.elementAt(i).elementAt(j));
if (j != sol.elementAt(i).size() - 1)
System.out.print(" ");
}
System.out.print("]");
}
}
// Driver Code
public static void main(String[] args)
{
int[] Vec = { 1, 7, 15, 29, 11, 9 };
Vector<Vector<Integer>> sol = partition(Vec);
// If partition possible
if (sol.size() > 0)
Print_Partition(sol);
else
System.out.println("-1");
}
}
// This code is contributed by
// sanjeev2552
Python
# Python3 program to partition an array of
# non-negative integers into two subsets
# such that average of both the subsets are equal
dp = []
res = []
original = []
total_size = int(0)
# Function that returns true if it is possible
# to use elements with index = ind to construct
# a set of s ize = curr_size whose sum is curr_sum.
def possible(index, curr_sum, curr_size):
index = int(index)
curr_sum = int(curr_sum)
curr_size = int(curr_size)
global dp, res
# Base cases
if curr_size == 0:
return (curr_sum == 0)
if index >= total_size:
return False
# Which means curr_sum cant be
# found for curr_size
if dp[index][curr_sum][curr_size] == False:
return False
if curr_sum >= original[index]:
res.append(original[index])
# Checks if taking this element
# at index i leads to a solution
if possible(index + 1,
curr_sum - original[index],
curr_size - 1):
return True
res.pop()
# Checks if not taking this element at
# index i leads to a solution
if possible(index + 1, curr_sum, curr_size):
return True
# If no solution has been found
dp[index][curr_sum][curr_size] = False
return False
# Function to find two partitions
# having equal average
def partition(Vec):
global dp, original, res, total_size
# Sort the vector
Vec.sort()
if len(original) > 0:
original.clear()
original = Vec
if len(dp) > 0:
dp.clear()
if len(res) > 0:
res.clear()
total_sum = 0
total_size = len(Vec)
for i in range(total_size):
total_sum += Vec[i]
# Building the memoization table
dp = [[[True for _ in range(total_size)]
for _ in range(total_sum + 1)]
for _ in range(len(original))]
for i in range(1, total_size):
# Sum_of_Set1 has to be an integer
if (total_sum * i) % total_size != 0:
continue
Sum_of_Set1 = (total_sum * i) / total_size
# We build our solution vector if its possible
# to find subsets that match our criteria
# using a recursive function
if possible(0, Sum_of_Set1, i):
# Find out the elements in Vec,
# not in res and return the result.
ptr1 = 0
ptr2 = 0
res1 = res
res2 = []
while ptr1 < len(Vec) or ptr2 < len(res):
if (ptr2 < len(res) and
res[ptr2] == Vec[ptr1]):
ptr1 += 1
ptr2 += 1
continue
res2.append(Vec[ptr1])
ptr1 += 1
ans = []
ans.append(res1)
ans.append(res2)
return ans
# If we havent found any such subset.
ans = []
return ans
# Driver code
Vec = [ 1, 7, 15, 29, 11, 9 ]
sol = partition(Vec)
if len(sol) > 0:
print(sol)
else:
print("-1")
# This code is contributed by saishashank1
C#
// C# program to Partition an array of
// non-negative integers into two subsets
// such that average of both the subsets are equal
using System;
using System.Collections;
class GFG{
static bool[,,] dp;
static ArrayList res = new ArrayList();
static int[] original;
static int total_size;
// Function that returns true if it is possible to
// use elements with index = ind to construct a set of s
// ize = curr_size whose sum is curr_sum.
static bool possible(int index, int curr_sum,
int curr_size)
{
// base cases
if (curr_size == 0)
return (curr_sum == 0);
if (index >= total_size)
return false;
// Which means curr_sum cant be
// found for curr_size
if (dp[index, curr_sum, curr_size] == false)
return false;
if (curr_sum >= original[index])
{
res.Add(original[index]);
// Checks if taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum -
original[index], curr_size - 1))
return true;
res.Remove(res[res.Count - 1]);
}
// Checks if not taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum, curr_size))
return true;
dp[index, curr_sum, curr_size] = false;
// If no solution has been found
return dp[index, curr_sum, curr_size];
}
// Function to find two Partitions
// having equal average
static ArrayList partition(int[] Vec)
{
// Sort the vector
Array.Sort(Vec);
original = Vec;
res.Clear();
int total_sum = 0;
total_size = Vec.Length;
for(int i = 0; i < total_size; ++i)
total_sum += Vec[i];
// Building the memoization table
dp = new bool[original.Length,
total_sum + 1,
total_size];
for(int i = 0; i < original.Length; i++)
for(int j = 0; j < total_sum + 1; j++)
for(int k = 0; k < total_size; k++)
dp[i, j, k] = true;
for(int i = 1; i < total_size; i++)
{
// Sum_of_Set1 has to be an integer
if ((total_sum * i) % total_size != 0)
continue;
int Sum_of_Set1 = (total_sum * i) / total_size;
// We build our solution vector if its possible
// to find subsets that match our criteria
// using a recursive function
if (possible(0, Sum_of_Set1, i))
{
// Find out the elements in Vec, not in
// res and return the result.
int ptr1 = 0, ptr2 = 0;
ArrayList res1 = new ArrayList(res);
ArrayList res2 = new ArrayList();
while (ptr1 < Vec.Length || ptr2 < res.Count)
{
if (ptr2 < res.Count &&
(int)res[ptr2] == Vec[ptr1])
{
ptr1++;
ptr2++;
continue;
}
res2.Add(Vec[ptr1]);
ptr1++;
}
ArrayList ans = new ArrayList();
ans.Add(res1);
ans.Add(res2);
return ans;
}
}
// If we havent found any such subset.
ArrayList ans2 = new ArrayList();
return ans2;
}
// Function to print partitions
static void Print_Partition(ArrayList sol)
{
// Print two partitions
for(int i = 0; i < sol.Count; i++)
{
Console.Write("[");
for(int j = 0; j < ((ArrayList)sol[i]).Count; j++)
{
Console.Write((int)((ArrayList)sol[i])[j]);
if (j != ((ArrayList)sol[i]).Count - 1)
Console.Write(" ");
}
Console.Write("] ");
}
}
// Driver Code
public static void Main(string[] args)
{
int[] Vec = { 1, 7, 15, 29, 11, 9 };
ArrayList sol = partition(Vec);
// If partition possible
if (sol.Count > 0)
Print_Partition(sol);
else
Console.Write("-1");
}
}
// This code is contributed by rutvik_56
JavaScript
// JS program to Partition an array of
// non-negative integers into two subsets
// such that average of both the subsets are equal
let dp = [];
let res = [];
let original = [];
let total_size;
// Function that returns true if it is possible to
// use elements with index = ind to construct a set of s
// ize = curr_size whose sum is curr_sum.
function possible(index, curr_sum, curr_size)
{
// base cases
if (curr_size == 0)
return (curr_sum == 0);
if (index >= total_size)
return false;
// Which means curr_sum cant be found for curr_size
if (dp[index][curr_sum][curr_size] == false)
return false;
if (curr_sum >= original[index]) {
res.push(original[index]);
// Checks if taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum -
original[index],
curr_size - 1))
return true;
res.pop();
}
// Checks if not taking this element at
// index i leads to a solution
if (possible(index + 1, curr_sum, curr_size))
return true;
// If no solution has been found
dp[index][curr_sum][curr_size] = false
return dp[index][curr_sum][curr_size];
}
// Function to find two Partitions having equal average
function partition(Vec)
{
// Sort the vector
Vec.sort();
original = [];
original = Vec;
dp = [];
res = [];
let total_sum = 0;
total_size = Vec.length;
for (var i = 0; i < total_size; ++i)
total_sum += Vec[i];
// building the memoization table
dp = new Array(original.length);
for (var i = 0; i < original.length; i++)
{
dp[i] = new Array(total_sum + 1);
for (var j = 0; j <= total_sum; j++)
{
dp[i][j] = new Array(total_size).fill(true);
}
}
for (var i = 1; i < total_size; i++) {
// Sum_of_Set1 has to be an integer
if ((total_sum * i) % total_size != 0)
continue;
var Sum_of_Set1 = (total_sum * i) / total_size;
// We build our solution vector if its possible
// to find subsets that match our criteria
// using a recursive function
if (possible(0, Sum_of_Set1, i)) {
// Find out the elements in Vec, not in
// res and return the result.
var ptr1 = 0, ptr2 = 0;
var res1 = res;
var res2 = [];
while (ptr1 < Vec.length || ptr2 < res.length)
{
if (ptr2 < res.length &&
res[ptr2] == Vec[ptr1])
{
ptr1++;
ptr2++;
continue;
}
res2.push(Vec[ptr1]);
ptr1++;
}
let ans = [];
ans.push(res1);
ans.push(res2);
return ans;
}
}
// If we havent found any such subset.
return -1;
}
// Driver code
let Vec = [1, 7, 15, 29, 11, 9 ];
let sol = partition(Vec);
console.log(sol)
Time Complexity: O(n3)
Auxiliary Space: O(n3)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem