Build a Matrix With Conditions - Problem

You are given a positive integer k. You are also given:

  • a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and
  • a 2D integer array colConditions of size m where colConditions[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 abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.
  • The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 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
Build Matrix With Conditions: k=3Input ConstraintsrowConditions = [[1,2],[3,2]]colConditions = [[2,1],[3,2]]1 above 2, 3 above 22 left of 1, 3 left of 2Graph Representation132Result Matrix300200100Topological Sort: Row Order [3,2,1], Column Order [1,3,2]✓ All constraints satisfied: 3 above 2 above 1, and positioned correctlyMatrix built successfully!
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
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen