Search⌘ K
AI Features

Build a Matrix with Conditions

Discover how to build a k by k matrix that places integers according to given row and column conditions. Learn to use topological sort to arrange elements while satisfying ordering constraints and handle cases where no valid arrangement exists.

Statement

You are given a positive integer kk, and you’re also given two conditions:

  • A 2D integer array row_conditions of size nn, where row_conditions[i] = [above[i], below[i]]. This means that above[i] must appear in a row above below[i] in the final matrix.

  • A 2D integer array col_conditions of size mm, where col_conditions[i] = [left[i], right[i]]. This means that left[i] must appear in a column to the left of right[i] in the final matrix.

Both arrays contain integers from 11 to kk.

Your task is to build a k ...