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 −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void subset_find(int arr[], int N) { unordered_map<int, int> my_map; int add = 0; for (int i = 0; i < N; i++) { add = (add + arr[i]) % N; if (add == 0) { cout << i + 1 << endl; for (int j = 0; j <= i; j++) cout << j + 1 << " "; return; } if (my_map.find(add) != my_map.end()) { cout << (i - my_map[add]) << endl; for (int j = my_map[add] + 1; j <= i; j++) cout << j + 1 << " "; return; } else my_map[add] = i; } } int main() { int arr[] = {3, 2, 7, 1, 9}; int N = sizeof(arr) / sizeof(arr[0]); subset_find(arr, N); }
{3, 2, 7, 1, 9}
2 1 2