Published on

Javascript Solution Group the People Given the Group Size They Belong To

Authors

Problem Overview

There are gathering of n people. People are divided into groups.

We have an array groupSizes. It stores size of group in which ith person is there.

Size of group of ith person is groupSizes[i].

We have to return a array of possible groups. Multiple correct solution possible.

For exact problem visit Leetcode Link;

Sample Input Output

Input: groupSizes = [3, 3, 3, 3, 3, 1, 3]
Output: [[5], [0, 1, 2], [3, 4, 6]]

Javascript Solution

  1. Create a Map where key will be group size and value will be list of all people who are in key size group.
  2. visit all element of map and for every key divide value in key sized array and push them in ans array.
  3. Return the final ans array.
/**
* @param {number[]} groupSizes
* @return {number[][]}
*/
var groupThePeople = function (groupSizes) {
const map = new Map()
const ans = []
// Creating a map key => groupSize and value => people in that size group
for (let i = 0; i < groupSizes.length; i++) {
// Time Complexity: O(N) and Space O(N)
if (!map.get(groupSizes[i])) {
// If current group size doest not exist in Map then
map.set(groupSizes[i], [i]) // then we are creating new array and assigning it to current size
} else {
map.get(groupSizes[i]).push(i) // else we pushed in existing array of people
}
}
// Here we are creating group of people with given size
// and pushing them in ans
// To avoid extra computation didn't used any inbuild array methods
for (const key of map.keys()) {
const value = map.get(key)
let valueLength = value.length
while (valueLength > 0) {
let tempArray = []
for (let j = 0; j < key; j++) {
tempArray.push(value[valueLength - 1])
valueLength--
}
ans.push(tempArray)
}
}
return ans
}

Submission Result

leetcode submission result