You are given a positive integer k. You are also given:
- a 2D integer array
rowConditionsof sizenwhererowConditions[i] = [abovei, belowi], and - a 2D integer array
colConditionsof sizemwherecolConditions[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
aboveishould appear in a row that is strictly above the row at which the numberbelowiappears for allifrom0ton - 1. - The number
leftishould appear in a column that is strictly left of the column at which the numberrightiappears for allifrom0tom - 1.
Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
Example 1:

Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] Output: [[3,0,0],[0,0,1],[0,2,0]] Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions. The row conditions are the following: - Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. - Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. The column conditions are the following: - Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. - Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. Note that there may be multiple correct answers.
Example 2:
Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]] Output: [] Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied. No matrix can satisfy all the conditions, so we return the empty matrix.
Constraints:
2 <= k <= 4001 <= rowConditions.length, colConditions.length <= 104rowConditions[i].length == colConditions[i].length == 21 <= abovei, belowi, lefti, righti <= kabovei != belowilefti != righti
Approach 01:
-
C++
-
Python
class Solution {
public:
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
// Perform topological sorting for rows
const vector<int> rowOrder = topologicalSort(rowConditions, k);
if (rowOrder.empty())
return {};
// Perform topological sorting for columns
const vector<int> colOrder = topologicalSort(colConditions, k);
if (colOrder.empty())
return {};
// Initialize the result matrix
vector<vector<int>> matrix(k, vector<int>(k));
vector<int> nodeToRowIndex(k + 1);
// Map nodes to their row indices based on rowOrder
for (int row = 0; row < k; ++row)
nodeToRowIndex[rowOrder[row]] = row;
// Fill in the matrix based on the column order
for (int col = 0; col < k; ++col) {
const int node = colOrder[col];
const int row = nodeToRowIndex[node];
matrix[row][col] = node;
}
return matrix;
}
private:
// Perform topological sort on a directed graph defined by conditions
vector<int> topologicalSort(const vector<vector<int>>& conditions, int n) {
vector<int> sortedOrder; // To store the topological order
vector<vector<int>> adjList(n + 1); // Adjacency list for the graph
vector<int> inDegrees(n + 1, 0); // In-degree count for each node
queue<int> zeroInDegreeNodes; // Queue for nodes with zero in-degree
// Build the graph from conditions
for (const vector<int>& condition : conditions) {
const int from = condition[0];
const int to = condition[1];
adjList[from].push_back(to);
++inDegrees[to];
}
// Initialize the queue with nodes having zero in-degree
for (int i = 1; i <= n; ++i)
if (inDegrees[i] == 0)
zeroInDegreeNodes.push(i);
// Perform Kahn's algorithm for topological sorting
while (!zeroInDegreeNodes.empty()) {
const int node = zeroInDegreeNodes.front();
zeroInDegreeNodes.pop();
sortedOrder.push_back(node);
for (const int neighbor : adjList[node])
if (--inDegrees[neighbor] == 0)
zeroInDegreeNodes.push(neighbor);
}
// Check if a valid topological sort was found
return sortedOrder.size() == n ? sortedOrder : vector<int>();
}
};
from collections import deque, defaultdict
from typing import List
class Solution:
def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:
# Perform topological sorting for rows
rowOrder = self.topologicalSort(rowConditions, k)
if not rowOrder:
return []
# Perform topological sorting for columns
colOrder = self.topologicalSort(colConditions, k)
if not colOrder:
return []
# Initialize the result matrix
matrix = [[0] * k for _ in range(k)]
nodeToRowIndex = [0] * (k + 1)
# Map nodes to their row indices based on rowOrder
for row, node in enumerate(rowOrder):
nodeToRowIndex[node] = row
# Fill in the matrix based on the column order
for col, node in enumerate(colOrder):
row = nodeToRowIndex[node]
matrix[row][col] = node
return matrix
def topologicalSort(self, conditions: List[List[int]], n: int) -> List[int]:
sortedOrder = [] # To store the topological order
adjList = defaultdict(list) # Adjacency list for the graph
inDegrees = [0] * (n + 1) # In-degree count for each node
zeroInDegreeNodes = deque() # Queue for nodes with zero in-degree
# Build the graph from conditions
for from_node, to_node in conditions:
adjList[from_node].append(to_node)
inDegrees[to_node] += 1
# Initialize the queue with nodes having zero in-degree
for i in range(1, n + 1):
if inDegrees[i] == 0:
zeroInDegreeNodes.append(i)
# Perform Kahn's algorithm for topological sorting
while zeroInDegreeNodes:
node = zeroInDegreeNodes.popleft()
sortedOrder.append(node)
for neighbor in adjList[node]:
inDegrees[neighbor] -= 1
if inDegrees[neighbor] == 0:
zeroInDegreeNodes.append(neighbor)
# Check if a valid topological sort was found
return sortedOrder if len(sortedOrder) == n else []
Time Complexity
- Topological Sorting:
The time complexity for performing topological sorting using Kahn’s algorithm is \( O(V + E) \), where \( V \) is the number of nodes (which is \( k \) in this case) and \( E \) is the number of edges in the graph (which depends on the size of
rowConditionsandcolConditions). - Matrix Construction:
After obtaining the topological order for rows and columns, constructing the matrix takes \( O(k^2) \) time, as it involves filling a \( k \times k \) matrix.
- Overall Time Complexity:
The overall time complexity is \( O(k^2 + E) \), where \( E \) is the number of edges in the graph formed by
rowConditionsandcolConditions.
Space Complexity
- Auxiliary Space:
The space complexity for storing the adjacency list, in-degrees, and topological sort order is \( O(k + E) \). Additionally, the result matrix requires \( O(k^2) \) space.
- Overall Space Complexity:
The overall space complexity is \( O(k^2 + E) \).