Group the People Given the Group Size They Belong To in C++


Suppose there are n people whose IDs are in range 0 to n - 1 and each person belongs exactly to one group. We have the array groupSizes of length n. This array is indicating that the group size each person belongs to, we have to find the groups there are and the people's IDs each group includes.

Suppose the input is like − [3,3,3,3,3,1,3], then the output is [[5], [0, 1, 2], [3, 4, 6]], Other possible solutions can be [[2,1,6],[5], [0,4,3]] or [[5], [0,6,2], [4,3,1]]

To solve this, we will follow these steps −

  • create one map m
  • for i in range 0 to size of given array a – 1
    • insert i into m[g[i]]
  • create one matrix called res
  • for each element i in map m
    • for j in range 0 to size of the list present at i
      • insert jth element of the array of i into temp
      • if size of temp = key of i
        • then insert temp into res as new row
        • clear the temp array
  • return res.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<vector<int>> groupThePeople(vector<int>& g) {
      map <int, vector <int> > m;
      for(int i = 0; i < g.size(); i++){
         m[g[i]].push_back(i);
      }
      vector < vector <int> > res;
      map <int, vector <int> > :: iterator i = m.begin();
      vector <int> temp;
      while(i != m.end()){
         for(int j = 0; j < i->second.size(); j++){
            temp.push_back(i->second[j]);
            if(temp.size() == i->first){
               res.push_back(temp);
               temp.clear();
            }
         }
         i++;
      }
      return res;
   }
};
main(){
   vector<int> v = {3,3,3,3,3,1,3};
   Solution ob;
   print_vector(ob.groupThePeople(v));
}

Input

[3,3,3,3,3,1,3]

Output

[[5, ],[0, 1, 2, ],[3, 4, 6, ],]

Updated on: 02-May-2020

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements