Build a Matrix With Conditions - Problem
You are given a positive integer k. You are also given:
- a 2D integer array
rowConditionsof sizenwhererowConditions[i] = [abovei, belowi], and - a 2D integer array
colConditionsof sizemwherecolConditions[i] = [lefti, righti].
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
aboveishould appear in a row that is strictly above the row at which the numberbelowiappears for allifrom0ton - 1. - The number
leftishould appear in a column that is strictly left of the column at which the numberrightiappears for allifrom0tom - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
Input & Output
Example 1 — Basic Case
$
Input:
k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]
›
Output:
[[3,0,0],[2,0,0],[1,0,0]]
💡 Note:
Number 1 must be above 2, and 3 must be above 2 (row constraints). Number 2 must be left of 1, and 3 must be left of 2 (column constraints). One valid arrangement places 1 at (2,0), 2 at (1,0), and 3 at (0,0).
Example 2 — No Solution
$
Input:
k = 3, rowConditions = [[1,2],[2,1]], colConditions = []
›
Output:
[]
💡 Note:
Impossible constraints: 1 must be above 2 AND 2 must be above 1. This creates a cycle, so no valid matrix exists.
Example 3 — Single Element
$
Input:
k = 1, rowConditions = [], colConditions = []
›
Output:
[[1]]
💡 Note:
Only one number to place with no constraints, so place 1 at position (0,0).
Constraints
- 2 ≤ k ≤ 400
- 1 ≤ rowConditions.length, colConditions.length ≤ 104
- rowConditions[i] = [abovei, belowi]
- colConditions[i] = [lefti, righti]
- 1 ≤ abovei, belowi, lefti, righti ≤ k
Visualization
Tap to expand
Understanding the Visualization
1
Input Constraints
Row and column positioning rules for numbers 1 to k
2
Convert to Graphs
Transform constraints into directed dependency graphs
3
Build Matrix
Place numbers according to topologically sorted orderings
Key Takeaway
🎯 Key Insight: Convert positioning constraints to directed graphs and use topological sorting to find valid orderings
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code