Sort Items by Groups Respecting Dependencies
There are n items belonging to zero or one of m groups (group[i] == -1 means no group). Given beforeItems[i], the items that must come before item i, return any arrangement of items such that (1) items in the same group are contiguous and (2) all beforeItems dependencies are respected. Return an empty list if no valid arrangement exists.
Open official problem prompt ↗Produce a single linear order of items that honors both the per-item precedence rules and the requirement that same-group items form a contiguous block.
Scheduling conference talks: sessions (groups) must run back-to-back in a sensible order, and within each session the talks have their own prerequisite ordering.
- Input
- n = 8, m = 2, group = [-1, -1, 1, 0, 0, 1, 0, -1], beforeItems = [[], [6], [5], [6], [3, 6], [], [], []]
- Output
- [6, 3, 4, 5, 2, 0, 7, 1]
- Why
- Every dependency is respected and each group's items are consecutive: group 0 = {6,3,4}, group 1 = {5,2}, and the singletons follow.
1 <= m <= n <= 3 * 10^4group.length == beforeItems.length == n-1 <= group[i] <= m - 10 <= beforeItems[i].length <= n - 10 <= beforeItems[i][j] <= n - 1beforeItems[i] does not contain i and has no duplicates