Build a Matrix With Conditions Problem
Description
LeetCode Problem 2392.
You are given a positive integer k. You are also given:
- a 2D integer array
rowConditionsof sizenwhererowConditions[i] = [above_i, below_i], and - a 2D integer array
colConditionsof sizemwherecolConditions[i] = [left_i, right_i].
The two arrays contain integers from 1 to k.
You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0.
The matrix should also satisfy the following conditions:
- The number
above_ishould appear in a row that is strictly above the row at which the numberbelow_iappears for allifrom0ton - 1. - The number
left_ishould appear in a column that is strictly left of the column at which the numberright_iappears for allifrom0tom - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
Example 1:

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 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix.
- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix.
The column conditions are the following:
- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix.
- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix.
Note that there may be multiple correct answers.
Example 2:
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.
Constraints:
2 <= k <= 4001 <= rowConditions.length, colConditions.length <= 10^4rowConditions[i].length == colConditions[i].length == 21 <= above_i, below_i, left_i, right_i <= kabove_i != below_ileft_i != right_i
Solution
Approach: Topological Sort
The row conditions and the column conditions are independent. Each set of conditions is a precedence graph on the numbers 1..k; a topological order gives a valid order of the numbers by row (or by column). If either graph has a cycle, no matrix exists and the answer is empty.
Otherwise the number at position i of the row order goes in row i, and its column is its position in the column order. All other cells are 0.
Complexity: time O(k^2 + n + m), space O(k^2), where n and m are the numbers of row and column conditions.
from collections import defaultdict, deque
class Solution:
def buildMatrix(
self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]
) -> List[List[int]]:
def f(cond):
g = defaultdict(list)
indeg = [0] * (k + 1)
for a, b in cond:
g[a].append(b)
indeg[b] += 1
q = deque([i for i, v in enumerate(indeg[1:], 1) if v == 0])
res = []
while q:
for _ in range(len(q)):
i = q.popleft()
res.append(i)
for j in g[i]:
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return None if len(res) != k else res
row = f(rowConditions)
col = f(colConditions)
if row is None or col is None:
return []
ans = [[0] * k for _ in range(k)]
m = [0] * (k + 1)
for i, v in enumerate(col):
m[v] = i
for i, v in enumerate(row):
ans[i][m[v]] = v
return ans