Build a Matrix With Conditions - Problem
Imagine you're organizing a seating arrangement where specific people must sit in particular positions relative to each other! ๐ช
You are given a positive integer k and need to build a k ร k matrix containing each number from 1 to k exactly once, with remaining cells filled with 0.
You must satisfy two types of ordering constraints:
- Row Conditions:
rowConditions[i] = [above_i, below_i]meansabove_imust appear in a row strictly abovebelow_i - Column Conditions:
colConditions[i] = [left_i, right_i]meansleft_imust appear in a column strictly to the left ofright_i
Goal: Return any valid matrix that satisfies all conditions, or an empty matrix if impossible.
This is essentially a 2D topological sorting problem! ๐ฏ
Input & Output
example_1.py โ Basic Case
$
Input:
k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]
โบ
Output:
[[3,0,0],[0,0,1],[0,2,0]] (or any valid arrangement)
๐ก Note:
Number 1 must be above 2, and 3 must be above 2 in rows. Number 2 must be left of 1, and 3 must be left of 2 in columns. The output satisfies: row order (3,1,2) and column order (2,1,3).
example_2.py โ Impossible Case
$
Input:
k = 3, rowConditions = [[1,2],[2,3],[3,1]], colConditions = [[2,1]]
โบ
Output:
[]
๐ก Note:
Row conditions create a cycle: 1โ2โ3โ1, making it impossible to arrange numbers in rows. When there's a cycle in dependencies, no valid arrangement exists.
example_3.py โ No Constraints
$
Input:
k = 2, rowConditions = [], colConditions = []
โบ
Output:
[[1,0],[0,2]] (or any valid arrangement)
๐ก Note:
With no constraints, any arrangement of numbers 1 and 2 in the 2ร2 matrix is valid. Each number appears exactly once with zeros filling remaining positions.
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Dependencies
Identify which numbers must come before others in rows and columns
2
Check for Conflicts
Use topological sorting to detect impossible circular dependencies
3
Determine Orderings
Find valid sequences for both row positions and column positions
4
Place Numbers
Position each number at the intersection of its assigned row and column
Key Takeaway
๐ฏ Key Insight: This problem cleverly combines two independent topological sorting problems - one for rows and one for columns. The beauty is recognizing that 2D constraints can be decomposed into separate 1D ordering problems, then recombined into the final matrix solution.
Time & Space Complexity
Time Complexity
O(k + n + m)
k nodes, n row conditions, m column conditions - each processed once
โ Linear Growth
Space Complexity
O(k + n + m)
Space for graphs, queues, and result arrays
โก Linearithmic Space
Constraints
- 2 โค k โค 400
- 1 โค rowConditions.length, colConditions.length โค 104
- rowConditions[i].length == colConditions[i].length == 2
- 1 โค abovei, belowi, lefti, righti โค k
- abovei โ belowi
- lefti โ righti
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code