Skip to main content
LeetCode 2392, Hard. Topics: Array, Graph Theory, Topological Sort, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

Problem

You are given a positive integer k. You are also given:
  • a 2D integer array rowConditions of size n where rowConditions[i] = [above_i, below_i], and
  • a 2D integer array colConditions of size m where colConditions[i] = [left_i, right_i].
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 above_i should appear in a row that is strictly above the row at which the number below_i appears for all i from 0 to n - 1.
  • The number left_i should appear in a column that is strictly left of the column at which the number right_i appears for all i from 0 to m - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.

Examples

Example 1

Constraints

  • 2 <= k <= 400
  • 1 <= rowConditions.length, colConditions.length <= 10^4
  • rowConditions[i].length == colConditions[i].length == 2
  • 1 <= above_i, below_i, left_i, right_i <= k
  • above_i != below_i
  • left_i != right_i

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode 250, NeetCode All.
Last modified on August 25, 2026