DEV Community

Cover image for 1203. Sort Items by Groups Respecting Dependencies
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

1203. Sort Items by Groups Respecting Dependencies

1203. Sort Items by Groups Respecting Dependencies

Difficulty: Hard

Topics: Principal, Depth-First Search, Breadth-First Search, Graph Theory, Topological Sort, Directed Acyclic Graph, Weekly Contest 155

There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to, and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.

Return a sorted list of the items such that:

  • The items that belong to the same group are next to each other in the sorted list.
  • There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).

Return any solution if there is more than one solution and return an empty list if there is no solution.

Example 1:

1359_ex1

  • Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
  • Output: [6,3,4,1,5,2,0,7]

Example 2:

  • Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
  • Output: []
  • Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.

Constraints:

  • 1 <= m <= n <= 3 * 10⁴
  • group.length == beforeItems.length == n
  • `-1 <= group[i] <= m - 1
  • 0 <= beforeItems[i].length <= n - 1
  • 0 <= beforeItems[i][j] <= n - 1
  • i != beforeItems[i][j]
  • beforeItems[i] does not contain duplicates elements.

Hint:

  1. Think of it as a graph problem.
  2. We need to find a topological order on the dependency graph.
  3. Build two graphs, one for the groups and another for the items.

Solution:

We decompose the problem into two coupled topological sorts: one over the items (from beforeItems) and one over the groups (induced only by cross-group dependencies). Both graphs must be acyclic for a valid arrangement to exist. After obtaining both orders, we bucket items by group using the item topological order (which preserves intra‑group constraints), then concatenate buckets following the group topological order. This yields a single sequence where every group's items are contiguous and every beforeItems constraint is honored. If either topological sort fails (cycle detected), we return an empty array.

Approach

  • Normalize groups: every ungrouped item (group[i] == -1) becomes its own unique group ID (m++). This prevents ungrouped items from being forced adjacent to one another.
  • Build two DAGs:
    • Item graph: for each before in beforeItems[i], add edge before → i, and bump itemIndeg[i].
    • Group graph: for each before → i where group[before] != group[i], add edge group[before] → group[i], and bump groupIndeg[group[i]]. (Same-group edges are skipped — they are already enforced by the item graph.)
  • Kahn's BFS topological sort on both graphs.
  • Validate: if either topological order length ≠ node count, a cycle exists → return [].
  • Bucket items: iterate itemOrder and append each item to buckets[group[item]] — this preserves relative item order within each group.
  • Emit result: iterate groupOrder and append each bucket's items in order.

Let's implement this solution in PHP: 1203. Sort Items by Groups Respecting Dependencies

`php
<?php
/**

  • @param Integer $n
  • @param Integer $m
  • @param Integer[] $group
  • @param Integer[][] $beforeItems
  • @return Integer[] / function sortItems(int $n, int $m, array $group, array $beforeItems): array { ... ... ... /*
    • go to ./solution.php */ }

/**

  • @param int $nodes
  • @param array $graph
  • @param array $indeg
  • @return array / function topoSort(int $nodes, array $graph, array $indeg): array { ... ... ... /*
    • go to ./solution.php */ }

// Test cases
echo sortItems(8, 2, [-1,-1,1,0,0,1,0,-1], [[],[6],[5],[6],[3,6],[],[],[]]) . "\n"; // Output: [6,3,4,1,5,2,0,7]
echo sortItems(8, 2, [-1,-1,1,0,0,1,0,-1], [[],[6],[5],[6],[3],[],[4],[]]) . "\n"; // Output: []
?>
`

Explanation

  • Why unique groups for ungrouped items: Leaving them as -1 would force all ungrouped items to be adjacent, which the problem does not require. Making each its own group lets them float anywhere the item constraints allow.
  • Why two separate graphs: The problem has two orthogonal ordering axes — item precedence and group adjacency. A single graph cannot encode both without creating false cycles (e.g., a same-group bidirectional item constraint would look like a group cycle).
  • Why group edges only on cross-group deps: Intra-group ordering is already governed by the item DAG. Adding it to the group DAG is redundant and can fabricate cycles where none really exist.
  • Why both cycles matter:
    • Item cycle → no valid item sequence exists.
    • Group cycle → group blocks cannot be placed consistently (Example 2 in the prompt).
    • Both must be acyclic.
  • Why bucketing preserves correctness:
    • Intra-group: within a bucket, items appear in itemOrder, so any before → i in the same group is respected.
    • Cross-group: the group DAG has an edge G_before → G_after, so groupOrder places all of G_before before all of G_after, guaranteeing the dependency.
  • Edge cases covered: single item, all-ungrouped items, chains within one group, cycles only at the item level, cycles only at the group level, and empty beforeItems.

Complexity Analysis

  • Time: O(n + m + E) where E = Σ |beforeItems[i]|.
    • Group normalization: O(n)
    • Building graphs: O(n + E)
    • Two topological sorts: O(n + E) and O(m + E)
    • Bucketing: O(n); result assembly: O(n)
  • Space: O(n + m + E)
    • Two adjacency lists + two indegree arrays: O(n + m + E)
    • Two topological orders, buckets, and result: O(n + m)

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
Buy Me A Coffee

If you want more helpful content like this, feel free to follow me:

Top comments (0)