You are given an integer and two sets of conditions: rowConditions and colConditions. Each condition is a pair [u, v] meaning must appear in a row (or column) above (or to the left of) . You need to build a matrix containing the numbers 1 to that satisfies all conditions. If no such matrix exists, return an empty array.
This "Hard" problem is used by Google and Meta to test your knowledge of Graph theory and your ability to decouple multi-dimensional constraints. It requires you to realize that the row positions and column positions can be determined completely independently of each other using the same algorithm.
The core pattern is Topological Sort. You treat the row conditions as a directed graph where an edge u -> v means comes before . You perform a topological sort to find a valid linear ordering of the numbers 1 to for the rows. You do the same for the column conditions. If either graph has a cycle (meaning topological sort is impossible), then no valid matrix exists. Finally, you use the resulting orderings to place each number i at coordinates (row_index[i], col_index[i]).
, rowConditions = [[1, 2]], colConditions = [[2, 1]]
A common error is trying to solve the row and column constraints simultaneously, which is much more difficult. Another is failing to detect cycles in the graph, which should lead to an empty result. Using Kahn's algorithm or DFS for topological sort is fine, but you must ensure you handle all numbers, even those not mentioned in the conditions.
Master Topological Sort. It's the standard tool for any problem involving "precedence" or "orderings." Also, remember that in 2D grid problems, you can often solve the X and Y dimensions independently if the constraints don't link them together.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Strange Printer II | Hard | Solve | |
| Minimum Operations to Remove Adjacent Ones in Matrix | Hard | Solve | |
| Sequence Reconstruction | Medium | Solve | |
| Rank Transform of a Matrix | Hard | Solve | |
| Minimize Maximum Value in a Grid | Hard | Solve |