Find if there is any subset of size K with 0 sum in an array of -1 and +1 in C++


In this problem, we are given an array arr[] consisting of only 1 and -1 and an integer value k. Our task is to find if there is any subset of size K with 0 sum in an array of -1 and +1. 

Let’s take an example to understand the problem,

Input: arr[] = {-1, 1, -1, -1, 1 , 1, -1}, k = 4

Output: YES

Explanation:

Subset of size 4, {-1, 1, -1, 1}. Sum = -1 + 1 - 1 + 1 = 0

Solution Approach: 

We need to check if there exists any subset of size k whose sum is equal to 0. As a subset we can consider any element from the array, the sum will be 0, if there will be an equal number of 1 and -1 in the subset. This is possible only if the size of the subset is even.

Simply,

If k is even, return true.
If k is odd, return false.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int countOne(int a[], int n) {
   
   int i, count = 0;
   for (i = 0; i < n; i++)
      if (a[i] == 1)
         count++;
   return count;
}

bool isSubSetSumZeroFound(int arr[], int n, int K) {
   
   int totalOne = countOne(arr, n);
   int totalNegOne = n - totalOne;
   return (K % 2 == 0 && totalOne >= K / 2 && totalNegOne >= K / 2);
}

int main() {
   
   int arr[] = { 1, 1, -1, -1, 1, -1, 1, 1, -1 };
   int size = sizeof(arr) / sizeof(arr[0]);
   int K = 4;
   if (isSubSetSumZeroFound(arr, size, K))
      cout<<"Subset of size "<<K<<" with sum of all elements 0 exists.";
   else
      cout<<"No subset found";
   return 0;
}

Output

Subset of size 4 with sum of all elements 0 exists.

Updated on: 22-Jan-2021

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements