#2392
Build a Matrix With Conditions
HardArrayGraph TheoryTopological SortMatrixGraph TheoryTopological SortDependency Resolution
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n + m) |
| Space | O(n²) | O(n + m) |
💡
Intuition
Time O(n + m)Space O(n + m)
The optimal solution utilizes graph theory and topological sorting to determine the order of numbers based on the given conditions. This approach is efficient and directly addresses the constraints of the problem.
⚙️
Algorithm
3 steps- 1Step 1: Construct a directed graph where each number points to the numbers that must be below or to the right of it.
- 2Step 2: Perform a topological sort on the graph to determine a valid order of numbers.
- 3Step 3: Place the sorted numbers in the matrix according to their positions derived from the topological sort.
solution.py41 lines
1from collections import defaultdict, deque
2
3def buildMatrix(k, rowConditions, colConditions):
4 row_graph = defaultdict(list)
5 row_indegree = [0] * (k + 1)
6 col_graph = defaultdict(list)
7 col_indegree = [0] * (k + 1)
8
9 for above, below in rowConditions:
10 row_graph[above].append(below)
11 row_indegree[below] += 1
12 for left, right in colConditions:
13 col_graph[left].append(right)
14 col_indegree[right] += 1
15
16 row_order = topologicalSort(row_graph, row_indegree, k)
17 col_order = topologicalSort(col_graph, col_indegree, k)
18
19 if not row_order or not col_order:
20 return []
21
22 matrix = [[0] * k for _ in range(k)]
23 for i in range(k):
24 matrix[row_order[i]][col_order[i]] = i + 1
25 return matrix
26
27
28def topologicalSort(graph, indegree, k):
29 queue = deque()
30 for i in range(1, k + 1):
31 if indegree[i] == 0:
32 queue.append(i)
33 order = []
34 while queue:
35 node = queue.popleft()
36 order.append(node)
37 for neighbor in graph[node]:
38 indegree[neighbor] -= 1
39 if indegree[neighbor] == 0:
40 queue.append(neighbor)
41 return order if len(order) == k else []ℹ
Complexity note: The time complexity is O(n + m) where n is the number of row conditions and m is the number of column conditions. The space complexity is O(n + m) for storing the graph and indegree arrays.
- 1Understanding the problem as a graph allows for efficient ordering of elements.
- 2Topological sorting is crucial for resolving dependencies in directed graphs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.