Problem 1282

Abstract / Summary

Group people into lists based on the group size each person specifies.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1282.py

class Solution:
    def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
        groups = defaultdict(set)
        for id, g in enumerate(groupSizes):
            groups[g].add(id)

        result = []
        for g in sorted(groups):
            current = []
            for c in groups[g]:
                current.append(c)
                if len(current) == g:
                    result.append(current)
                    current = []

        return result
16 lines | 494 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 88% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method groupThePeople. The method receives a list groupSizes where each element indicates the desired size of the group to which the person (identified by the element’s index) belongs. The algorithm groups the indices into sub-lists such that each sub-list contains exactly the number of members specified by the corresponding group size. The result is a list of these groups.

Key Steps

Collecting indices by required group size

groups = defaultdict(set)
for id, g in enumerate(groupSizes):
    groups[g].add(id)

In this phase the code iterates over groupSizes with enumerate, pairing each person’s identifier (id) with the required group size (g). A defaultdict of sets stores the identifiers for each distinct group size. Using a set guarantees that each identifier appears only once for its size, and insertion is performed in constant time.

Preparing the final collection

result = []
for g in sorted(groups):
    current = []
    for c in groups[g]:
        current.append(c)
        if len(current) == g:
            result.append(current)
            current = []

The algorithm processes the distinct group sizes in ascending order, which yields a deterministic ordering of groups in the output. For each size g, it iterates over the stored identifiers. A temporary list current accumulates identifiers until its length matches the required size g. When the target size is reached, current is appended to result and a fresh list is started for the next batch of the same size.

Returning the assembled groups

return result

After all identifiers have been allocated to groups, the method returns the list result, which contains sub-lists each satisfying the size constraint.

Edge Cases Handled

When the input contains a group size of 1, the inner loop adds the single identifier to current, immediately satisfies the size condition, and appends a one-element list to result.

If the entire population belongs to a single group (e.g., all entries in groupSizes are equal to len(groupSizes)), the set for that size will contain every identifier. The inner loop will fill current exactly once, producing a single group that includes all people.

The code also gracefully handles multiple distinct group sizes appearing in any order within groupSizes. By sorting the keys of groups, the algorithm ensures that groups are emitted in a predictable sequence regardless of the original ordering.

Because a set is used to store identifiers, any accidental duplicate identifiers for the same size would be collapsed, preventing the creation of oversized groups. However, the problem specification guarantees unique identifiers, so this behavior aligns with the intended logic.

Performance Optimizations

The use of defaultdict(set) eliminates the need for explicit existence checks before inserting an identifier, allowing each insertion to occur in constant time.

Iterating over sorted(groups) processes each distinct group size exactly once, avoiding repeated scans of the input list.

The inner accumulation of identifiers into current avoids creating intermediate collections; identifiers are appended directly to the list that will become a final group. Once a group reaches its required size, the list is handed off to result and a new list is allocated, minimizing memory churn.

By iterating over the set of identifiers for a given size, the algorithm leverages the fast iteration characteristics of Python’s built-in set type. The overall flow processes each identifier a constant number of times, leading to an efficient traversal of the input data.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of friends, and everyone is holding a sign that says how many people want to be in their group. Some friends want to be in a group of two, and others want to be in a group of three. To organize this, the computer starts with an empty notebook. It walks down the line of friends one by one. For each friend, it looks at the number on their sign and writes their name on the page for that specific group number.

Once all the friends are written down in the notebook, the computer flips through the pages. It looks at the group of friends who want to be in a group of size three. It gathers them into little squads of three at a time. Then it does the same for the friends who want to be in a group of two. It keeps picking up friends from the list and placing them into a new container until that container is full and matches the size on their signs. Every time a container gets full, it is set aside as a completed group. This process repeats until every friend is tucked safely into their own perfect group.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.04 | σ = 0.98

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fsq C++
Garvit244 Python
JoshCrozier JS
keineahnung2345 C++
Krazune JS
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fsq C++
Garvit244 Python
JoshCrozier JavaScript
keineahnung2345 C++
Krazune JavaScript
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
31 links | 19 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality