Input: k =3, rowConditions =[[1,2],[3,2]], colConditions =[[2,1],[3,2]]Output:[[3,0,0],[0,0,1],[0,2,0]]Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.The row conditions are the following:- Number 1isin row 1, and number 2isin row 2, so 1is above 2in the matrix.- Number 3isin row 0, and number 2isin row 2, so 3is above 2in the matrix.The column conditions are the following:- Number 2isin column 1, and number 1isin column 2, so 2is left of 1in the matrix.- Number 3isin column 0, and number 2isin column 1, so 3is left of 2in the matrix.Note that there may be multiple correct answers.
Example 2:
1
2
3
4
Input: k =3, rowConditions =[[1,2],[2,3],[3,1],[2,3]], colConditions =[[2,1]]Output: []Explanation: From the first two conditions,3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.No matrix can satisfy all the conditions, so we return the empty matrix.
defbuild_matrix(k, rowConditions, colConditions):
row_order = topological_sort(k, rowConditions)
col_order = topological_sort(k, colConditions)
ifnot row_order ornot col_order:
return []
row_position = {num: i for i, num in enumerate(row_order)}
col_position = {num: i for i, num in enumerate(col_order)}
matrix = [[0] * k for _ in range(k)]
for num in range(1, k +1):
matrix[row_position[num]][col_position[num]] = num
return matrix
deftopological_sort(k, conditions):
graph = defaultdict(list)
indegree = [0] * (k +1)
for u, v in conditions:
graph[u].append(v)
indegree[v] +=1 queue = deque([i for i in range(1, k +1) if indegree[i] ==0])
sorted_order = []
while queue:
node = queue.popleft()
sorted_order.append(node)
for neighbor in graph[node]:
indegree[neighbor] -=1if indegree[neighbor] ==0:
queue.append(neighbor)
if len(sorted_order) != k:
return []
return sorted_order
⏰ Time complexity: O(k), where k is 1 dimension of the matrix.
Graph construction - Constructing the adjacency list and indegree array takes O(E) times, where E is number of edges in graph, and in this problem E is proportional to k, may be around k at a time
Topological Sort using Kahn’s algorithm - Initializing the queue with nodes having indegree 0 takes O(V) time, where V is number of nodes. V = k in the problem. Processing each node using BFS takes O(V+E), and V and E are proportional to k, hence O(k)
🧺 Space complexity: O(k)
Graph storage - requires O(V+E), which is O(k)
Queue for BFS requires O(V) ⇨ O(k)
Toposort for rows and columns required O(2V) ⇨ O(k)
Two HashMaps for row and column positions: O(V) ⇨ O(k)