#1203

Sort Items by Groups Respecting Dependencies

Hard
Depth-First SearchBreadth-First SearchGraph TheoryTopological SortGraph TheoryTopological SortDependency Resolution
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n + m)
💡

Intuition

Time O(n + m)Space O(n + m)

The optimal solution uses graph theory concepts, specifically topological sorting, to efficiently order the items while respecting both group and dependency constraints.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a graph for items and their dependencies.
  2. 2Step 2: Perform a topological sort on the items to respect the beforeItems constraints.
  3. 3Step 3: Group the sorted items based on their group assignments.
  4. 4Step 4: Sort each group individually and concatenate the results.
solution.py53 lines
1from collections import defaultdict, deque
2
3def sortItems(n, m, group, beforeItems):
4    # Step 1: Create a graph
5    item_graph = defaultdict(list)
6    in_degree = [0] * n
7    for i in range(n):
8        for before in beforeItems[i]:
9            item_graph[before].append(i)
10            in_degree[i] += 1
11    
12    # Step 2: Topological sort for items
13    item_order = topological_sort(n, in_degree, item_graph)
14    if not item_order:
15        return []
16    
17    # Step 3: Group items
18    group_graph = defaultdict(list)
19    group_in_degree = [0] * m
20    group_items = defaultdict(list)
21    for i in range(n):
22        g = group[i] if group[i] != -1 else m
23        group_items[g].append(i)
24        for before in beforeItems[i]:
25            before_group = group[before] if group[before] != -1 else m
26            if before_group != g:
27                group_graph[before_group].append(g)
28                group_in_degree[g] += 1
29    
30    # Step 4: Topological sort for groups
31    group_order = topological_sort(m + 1, group_in_degree, group_graph)
32    if not group_order:
33        return []
34    
35    # Step 5: Sort items in each group
36    result = []
37    for g in group_order:
38        if g in group_items:
39            result.extend(sorted(group_items[g]))
40    return result
41
42
43def topological_sort(n, in_degree, graph):
44    queue = deque([i for i in range(n) if in_degree[i] == 0])
45    order = []
46    while queue:
47        node = queue.popleft()
48        order.append(node)
49        for neighbor in graph[node]:
50            in_degree[neighbor] -= 1
51            if in_degree[neighbor] == 0:
52                queue.append(neighbor)
53    return order if len(order) == n else []

Complexity note: The time complexity is O(n + m) because we perform a topological sort on both items and groups, which involves visiting each node and edge once.

  • 1Understanding the problem as a graph with dependencies helps in visualizing the solution.
  • 2Topological sorting is crucial for resolving dependencies in both items and groups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.