Find Non-Empty Subset with Divisible Sum in C++



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
  • add := 0
  • for initialize i := 0, when i < N, update (increase i by 1), do −
    • add := (add + arr[i]) mod N
    • 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 −
      • print (i - my_map[add])
      • for initialize j := my_map[add] + 1, when j <= i, update (increase j by 1), do −
        • print j + 1
      • return
    • Otherwise
      • my_map[add] := i

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;
   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);
}

Input

{3, 2, 7, 1, 9}

Output

2
1 2
Updated on: 2020-08-28T08:06:17+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements