 All Problems
Build a Matrix With Conditions
hard
topological sort
graph
matrix
google
amazon
microsoft

Given k and two arrays rowConditions and colConditions where each condition [above, below] means above must appear in a strictly smaller row than below, and similarly for column conditions:

Build a k × k matrix with values 1..k each appearing exactly once, such that all conditions are satisfied. Return the matrix or an empty matrix if impossible.

Example:

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

Constraints:

  • 2 <= k <= 400
  • 1 <= rowConditions.length, colConditions.length <= 10^4
Run to check your code against the sample cases, or submit to run every case