Sort Items by Groups Respecting Dependencies - Problem

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.

Input & Output

Example 1 — Basic Case with Groups
$ 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]
💡 Note: Items 3,4,6 belong to group 0. Items 2,5 belong to group 1. Items 0,1,7 have no group. Dependencies: 6→1, 5→2, 6→3, 3→4, 6→4. Valid ordering respects both group constraints and dependencies.
Example 2 — No Groups
$ Input: n = 8, m = 2, group = [-1,-1,-1,-1,-1,-1,-1,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: [6,3,4,5,2,1,0,7]
💡 Note: All items ungrouped, only dependency constraints matter. Dependencies: 6→1, 5→2, 6→3, 3→4, 4→6 creates cycle, but 4→6 not in input, so [6,3,4,5,2,1,0,7] works.
Example 3 — Impossible Case
$ Input: n = 2, m = 1, group = [0,0], beforeItems = [[1],[0]]
Output: []
💡 Note: Items 0 and 1 both in group 0 but have circular dependency: 0 depends on 1, and 1 depends on 0. No valid ordering exists.

Constraints

  • 1 ≤ m ≤ n ≤ 3 × 104
  • group[i] == -1 or 0 ≤ group[i] < m
  • 0 ≤ beforeItems[i].length ≤ n - 1
  • 0 ≤ beforeItems[i][j] ≤ n - 1
  • i != beforeItems[i][j]
  • beforeItems[i] does not contain duplicates elements

Visualization

Tap to expand
INPUT ANALYSISn=8, m=2GroupsGroup 0: [3,4,6]Group 1: [2,5]No Group: [0,1,7]Dependencies6 → 1, 6 → 33 → 4, 6 → 45 → 2No cycles detectedChallenge:Group items togetherwhile respecting dependenciesTWO-LEVEL SORT1Build group dependency graph2Topologically sort groups3Build item dependency graphs4Sort items within each groupKahn's Algorithm• Calculate indegrees• Queue zero-indegree nodes• Process level by level• Update neighbor indegrees• Detect cycles if queue emptyTime: O(n + E)Space: O(n + m)FINAL RESULTValid Topological OrderOutput Array634152Constraints Satisfied:✓ Group 0 items together: 6,3,4✓ Group 1 items together: 5,2✓ Dependencies respected✓ No cycles createdAlternative Solutions:Multiple valid orderings possibleas long as constraints satisfiedKey Insight:This problem requires two-level topological sorting - first sort the groupsbased on inter-group dependencies, then sort items within each groupwhile respecting intra-group dependencies. Use Kahn\'s algorithm for both levels.TutorialsPoint - Sort Items by Groups Respecting Dependencies | Topological Sort
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
25.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen