Skip to content

Practice Build a Matrix With Conditions

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#2392
LeetCode Problem

Build a Matrix With Conditions

Problem Statement

Build a k by k matrix containing each integer 1 through k exactly once, with all other cells 0. Each rowConditions pair [above,below] requires the first value in a strictly earlier row, and each colConditions pair [left,right] requires the first in a strictly earlier column. Return any satisfying matrix, or [] if none exists.

Source: Build a Matrix With Conditions on LeetCode. Use the original task for its coding environment and submissions.

Examples

# 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]]

# Example 2

Input
k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]
Output
[]

Constraints

2 <= k <= 400
1 <= rowConditions.length, colConditions.length <= 10^4
rowConditions[i].length == colConditions[i].length == 2
1 <= abovei, belowi, lefti, righti <= k
abovei != belowi
lefti != righti

Related LeetCode Problems

Practice more problems similar to Build a Matrix With Conditions.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.