Python 1203.py
class Solution:
def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
size = n # == len(beforeItems)
# topological sort
def topsort(item, need, visited, output):
# recursive implementation
# each item only once
if item in visited:
return
visited.add(item)
# visit prerequisites
for next in need[item]:
topsort(next, need, visited, output)
# found the proper position
output.append(item)
# wrapper for topsort
def mysort(need):
output = []
visited = set()
if isinstance(need, list):
keys = range(len(need)) # list
else:
keys = need.keys() # dict
for node in keys:
topsort(node, need, visited, output)
# consistency check (loops are not allowed)
have = set()
for o in output:
for n in need[o]:
if n not in have:
return [] # cyclic dependency found
have.add(o)
return output
# convert "no group" to unique group ids
limit = max(group) + 1
for item in range(size):
if group[item] == -1:
group[item] = limit
limit += 1
# slice items into groups (I call them "blocks")
blocks = [ [] for _ in range(limit) ]
for item in range(size):
blocks[group[item]].append(item)
# order of blocks
order = [ [] for _ in range(limit) ] # I tried defaultdict(set) first,
# but lists are even faster for the given input
# despite their O(n) lookup
# sort each block
for id in range(limit):
if not blocks[id]:
continue # unused group ID
# extract prerequisites that happen to be in the same block
need = { s: [] for s in blocks[id] }
for s in blocks[id]:
for b in beforeItems[s]:
if b in blocks[id]:
# depends on an item in the same block
need [s] .append(b)
else:
# depends on an item in a different block
order[id].append(group[b])
blocks[id] = mysort(need)
# abort if cycle was found
if not blocks[id]:
return []
# sort blocks
output = mysort(order)
# push, push, push !
for o in output:
if blocks[o]:
yield from blocks[o]
Difficulty
and has an acceptance rate of about 66% (100k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Depth First Search
- Graph Theory
- Topological Sort
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 solves a dependency-ordering problem where items belong to groups and each item may require other items to appear earlier. The algorithm first normalizes group identifiers, then partitions items into “blocks” (one per group). Each block is internally topologically sorted, while a second topological sort determines the order of the blocks themselves. The final result is produced by concatenating the sorted items of each block in the block order.
Topological Sort Implementation
A recursive depth-first search is used to produce a linear ordering that respects prerequisite edges. The inner function topsort marks a node as visited, recursively processes all its outgoing edges, and finally appends the node to the output list. The wrapper mysort iterates over all keys (either a list index range or a dictionary key set), invokes topsort for each unvisited node, and then performs a consistency check that guarantees no edge points from a later node to an earlier one. If such a situation is detected, an empty list is returned to signal a cycle.
def topsort(item, need, visited, output):
if item in visited:
return
visited.add(item)
for next in need[item]:
topsort(next, need, visited, output)
output.append(item)
def mysort(need):
output = []
visited = set()
if isinstance(need, list):
keys = range(len(need))
else:
keys = need.keys()
for node in keys:
topsort(node, need, visited, output)
have = set()
for o in output:
for n in need[o]:
if n not in have:
return [] # cyclic dependency found
have.add(o)
return output
Group Normalization
Items that are not assigned to any group are given unique group identifiers that are larger than any existing group id. This ensures that every item belongs to exactly one block, simplifying later processing.
limit = max(group) + 1
for item in range(size):
if group[item] == -1:
group[item] = limit
limit += 1
Block Construction
A list of lists, blocks, is created with a slot for each group identifier. Items are appended to the list that corresponds to their (now normalized) group.
blocks = [ [] for _ in range(limit) ]
for item in range(size):
blocks[group[item]].append(item)
Intra-Block Sorting
For each non-empty block the algorithm extracts the subset of prerequisite edges that stay inside the same block, building a dictionary need that maps each item to its internal dependencies. Dependencies that cross block boundaries are recorded in order[id] as the group of the prerequisite item. The internal topological sort is then performed with mysort. If a cycle is discovered inside a block, the function returns an empty list, causing the overall solution to abort.
need = { s: [] for s in blocks[id] }
for s in blocks[id]:
for b in beforeItems[s]:
if b in blocks[id]:
need[s].append(b)
else:
order[id].append(group[b])
blocks[id] = mysort(need)
if not blocks[id]:
return []
Inter-Block Sorting
After each block has been internally sorted, the list order contains, for every block, the groups that must precede it because of cross-block dependencies. Treating order as a dependency graph among groups, a second call to mysort yields a valid ordering of the blocks.
output = mysort(order)
Final Assembly
The final result is generated by iterating over the block order and yielding the items of each block in their pre-computed internal order. The use of a generator (yield from) allows the function to produce the result lazily, which can be advantageous when the caller consumes the sequence incrementally.
for o in output:
if blocks[o]:
yield from blocks[o]
Edge Cases Handled
The code explicitly addresses items without an assigned group by allocating fresh group identifiers, guaranteeing that every item participates in the block-level processing. The consistency check inside mysort detects cycles both within a block and across blocks, returning an empty list when a cyclic dependency is present. Empty groups (blocks with no items) are safely skipped during intra-block sorting, preventing unnecessary work. The algorithm also tolerates an empty beforeItems list for any item, treating such items as having no prerequisites.
Performance Optimizations
The implementation favors plain Python lists over more complex data structures for the order adjacency representation, noting that list lookups are faster for the expected input size despite their linear search cost. The use of a set for visited and have provides O(1) membership checks during depth-first traversal and cycle verification. By separating intra-block and inter-block sorting, the algorithm reduces the size of each topological sort problem, which improves cache locality and limits recursion depth. The final generator-based output avoids constructing an intermediate large list, reducing memory pressure when the result is consumed incrementally.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of different toys and you want to organize them into a straight line on the floor. Some toys have special rules, like needing another specific toy to be placed down first. Keeping track of all these rules can be tricky, so this code acts like a very organized teacher.
First, it looks at all the toys and puts them into smaller boxes based on what group they belong to. If a toy is a loner and does not have a group, it gets a special brand new group all to itself.
Next, it visits each box to make sure every toy follows its rules. It checks if a toy needs another one from inside the same box to come first. It carefully writes down the right order for the toys inside that box. While doing this, it also remembers which boxes need to go before other boxes because of the rules the toys have.
Once every box has its toys standing in the correct order, it looks at the boxes themselves. It figures out which box should go first, which should go second, and so on, keeping all those complicated dependency rules in mind.
Finally, it walks through the boxes in that perfect order. As it walks, it picks up the toys from each box in the order it decided on earlier and places them all in one long, perfect line on the floor. Everything ends up where it belongs without any accidents.
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++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ |
Videos
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