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
Difficulty
and has an acceptance rate of about 88% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Hash Table
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Similar Problems
- problem 781: Rabbits in Forest
- problem 2790: Maximum Number of Groups With Increasing Length
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- 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