# Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have an array of n numbers; we have to find a non-empty subset such that the sum of elements of the subset is divisible by n. So, we have to output any such subset with its size and the indices of elements in the original array when it is present.

So, if the input is like [3, 2, 7, 1, 9], then the output will be [2], [1 2].

To solve this, we will follow these steps −

• Define one map my_map
• for initialize i := 0, when i < N, update (increase i by 1), do −
• if add is same as 0, then −
• print i + 1
• for initialize j := 0, when j <= i, update (increase j by 1), do −
• print j + 1
• return
• if add in my_map, then −
• for initialize j := my_map[add] + 1, when j <= i, update (increase j by 1), do −
• print j + 1
• return
• Otherwise

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void subset_find(int arr[], int N) {
unordered_map<int, int> my_map;
for (int i = 0; i < N; i++) {
cout << i + 1 << endl;
for (int j = 0; j <= i; j++)
cout << j + 1 << " ";
return;
}
cout << (i - my_map[add]) << endl;
for (int j = my_map[add] + 1; j <= i; j++)
cout << j + 1 << " ";
return;
}
else
}
}
int main() {
int arr[] = {3, 2, 7, 1, 9};
int N = sizeof(arr) / sizeof(arr[0]);
subset_find(arr, N);
}

## Input

{3, 2, 7, 1, 9}

## Output

2
1 2
Updated on 28-Aug-2020 08:06:17