Topological sort, but with a certain kind of grouping
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
A plain topological sort orders items so every prerequisite appears before the item that depends on it. The grouped version adds another rule: items belonging to the same group should appear together, or at least respect a group-level ordering as well. That turns one DAG problem into two related DAGs that have to stay consistent.
Why Grouping Changes the Problem
In an ordinary DAG, each node is independent except for edges. Grouping introduces structure above the node level. For example, tasks may belong to teams, build steps may belong to modules, or lessons may belong to chapters.
If the requirement is that grouped items stay contiguous, then you cannot simply topologically sort all items and hope for a good result. Dependencies can cross group boundaries, so you need a strategy that orders groups first and items second.
A useful mental model is:
- Build an item graph for dependencies between individual items.
- Build a group graph for dependencies induced by cross-group edges.
- Topologically sort the groups.
- Within each group, topologically sort that group's items.
This is the core idea behind many accepted solutions to grouped-ordering problems.
Two-Level Topological Sort
Suppose item a in group G1 must come before item b in group G2. That single edge implies both:
- '
amust precedebin the item graph.' - '
G1must precedeG2in the group graph.'
Once you compute indegrees for both layers, Kahn's algorithm works well.
The helper returns None if a cycle exists.
A Grouped Example
The next example keeps groups contiguous. Each item belongs to a group, and before_items[i] lists prerequisites for item i.
Ungrouped items are assigned unique synthetic groups so the algorithm can treat everything uniformly.
When This Approach Works
This two-level approach works when the grouping rule is hierarchical: every item belongs to exactly one group, and the goal is to order groups plus the items within them. It is especially useful for package builds, deployment phases, curriculum ordering, and batch jobs.
It is less suitable when items may belong to multiple groups or when the grouping rule is soft rather than strict. In those cases, you are solving a different optimization problem, not just a DAG ordering problem.
Detecting Impossible Inputs
A grouped topological sort can fail for two independent reasons.
First, the item graph may contain a cycle, such as a -> b -> c -> a. Second, the group graph may contain a cycle induced by cross-group prerequisites even if no single group contains a cycle internally.
That is why checking only one graph is not enough. You must validate both layers.
Common Pitfalls
The biggest mistake is to topologically sort items once and then try to rearrange the result into groups afterward. That can silently break dependency constraints.
Another common bug is forgetting to create synthetic groups for ungrouped items. Leaving them all in a single placeholder bucket can force unrelated nodes together and create false constraints.
It is also easy to double-count cross-group edges. Using a set for group edges prevents inflated indegrees and avoids incorrect cycle detection.
Summary
- Grouped topological sort is usually a two-level DAG problem.
- Cross-group item edges imply dependencies in the group graph.
- Kahn's algorithm works well for both item and group ordering.
- Assign unique groups to ungrouped items if contiguity matters.
- Validate both the item graph and the group graph for cycles.
Related reading
- Topological sort in OCaml
- Topological sort of cyclic graph with minimum number of violated edges
- Topological sort to find the number of paths to t
- Topological sort using DFS without recursion
- Topological sorting in PHP
- Tornado generator resume on any future in list
- Topology-matching algorithm for finding 2D lattice in a 3D lattice
- Tournament bracket placement algorithm

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.