SDE & MLE Prep

2392. Build a Matrix With Conditions

Asked at 1Google22

Problem

Build a k×k matrix containing each number 1…k exactly once (the remaining cells are 0) such that for every [above, below] in rowConditions, above is in a strictly higher row than below, and for every [left, right] in colConditions, left is in a strictly earlier column than right. Return any such matrix, or an empty matrix if none exists.

Example: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] → [[3,0,0],[0,0,1],[0,2,0]] (one valid answer)

Constraints: k ≤ 400.

Rows and columns are independent. Topologically sort the numbers 1..k by rowConditions (gives each number's row) and separately by colConditions (its column); a cycle in either means no answer. Place number v at (row[v], col[v]) — every row and column gets exactly one number. Any valid matrix is accepted.

Complexity: O(k² + conditions) (the k × k output dominates).

class Solution:
    def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:
        def topo(conds):
            adj, indeg = defaultdict(list), [0] * (k + 1)
            for a, b in conds:
                adj[a].append(b)
                indeg[b] += 1
            q = deque(v for v in range(1, k + 1) if indeg[v] == 0)
            order = []
            while q:
                v = q.popleft()
                order.append(v)
                for w in adj[v]:
                    indeg[w] -= 1
                    if indeg[w] == 0:
                        q.append(w)
            return {v: i for i, v in enumerate(order)} if len(order) == k else None

        row, col = topo(rowConditions), topo(colConditions)
        if row is None or col is None:
            return []
        m = [[0] * k for _ in range(k)]
        for v in range(1, k + 1):
            m[row[v]][col[v]] = v
        return m