LeetCode 1203 Sort Items by Groups Respecting Dependencies - Solution

The core idea

Two-level topological sort.

First, assign each -1 group item to its own unique group. This simplifies handling.

Build two graphs:

  1. Item graph: edges between items based on beforeItems.
  2. Group graph: if item a (group X) depends on item b (group Y) where X ≠ Y, add edge Y → X.

Topologically sort the group graph to get group order. Then, for each group, topologically sort its items.

Concatenate the sorted items in group order.