So confusing…
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.Return a list of groups such that each person i is in a group of size groupSizes[i].Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Grab those unique Ids 🧮
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
  • groupSizes is an array of integers(numbers)
  • Each person is an index, that’s the unique ID
  • Each group’s size is stored in the groupSizes array
  • groupSizes[Person’s Id] = group size of this Person
  • Each person has ONLY ONE group
  • Every person MUST BE in a group
  • Return ANY answers
  • Each input(array of numbers) will always have AT LEAST 1 valid output
You heard the captain! 🚀
let result = [], groups = {};
const groupThePeople = function(groupSizes) {
let result = [], groups = {};

groupSizes.forEach((size, index) => {
if (size in groups) { ...

... if (size in groups) {
} else {
groups[size] = [index]
} ...
if (size in groups) {
if (groups[size].length < size) {
groups[size].push(index)
}


} else {
groups[size] = [index]
}
...if (groups[size].length === size) {

}...
if (groups[size].length === size) {
result.push(groups[size]);
}
if (groups[size].length === size) {
result.push(groups[size]);
groups[size] = [];

}
const groupThePeople = function(groupSizes) {
let result = [], groups = {};

groupSizes.forEach((size, index) => {
if (size in groups) {
if (groups[size].length < size) {
groups[size].push(index)
}

} else {
groups[size] = [index]
}

if (groups[size].length === size) {
result.push(groups[size]);
groups[size] = [];
}
})
return result;
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store