LeetCode 1203 Sort Items by Groups Respecting Dependencies - Example and Complexity Analysis

Walkthrough and analysis

Trace simplified example with 4 items, 2 groups.

Items 0,1 in group 0. Items 2,3 in group 1. Dependencies: 2 depends on 0 (cross-group), 3 depends on 2 (same group).

Group graph: edge from group 0 → group 1 (because 2 depends on 0). Group order: [0, 1].

Group 0 items: topological sort of {0, 1}. Say [0, 1]. Group 1 items: 3 depends on 2. Order: [2, 3].

Final: [0, 1, 2, 3].

Build graphs: O(n+E)O(n + E) where E is total dependencies. Two topological sorts: O(n+E)O(n + E) total. Space: O(n+E)O(n + E).