Build a Matrix with Conditions

Place [1..k] in a k×k grid satisfying row and column ordering constraints — two independent topological sorts.

Hard
Time O(k^2) Space O(k^2)
LeetCode
6 min read
topological-sort

Problem#

Place numbers [1..k] in a k × k grid (rest zeroes) so that for every “row condition” [a, b], a is in a row before b; same for column conditions. Return any valid grid, or [].

Examples#

  • k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] → a valid placement.

Approach#

Topological sort [1..k] twice (independently): once on row constraints, once on column constraints. The resulting orders give each number’s row and column. Construct the grid by placing each v at (rowRank[v], colRank[v]).

Solution#

Build a Matrix with Conditions
class Solution {
public:
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) {
auto topo = [&](vector<vector<int>>& cond) {
vector<vector<int>> adj(k + 1);
vector<int> indeg(k + 1, 0);
for (auto& c : cond) {
adj[c[0]].push_back(c[1]);
++indeg[c[1]];
}
queue<int> q;
for (int i = 1; i <= k; ++i) if (indeg[i] == 0) q.push(i);
vector<int> order;
while (!q.empty()) {
int u = q.front(); q.pop();
order.push_back(u);
for (int v : adj[u]) if (--indeg[v] == 0) q.push(v);
}
return (int)order.size() == k ? order : vector<int>{};
};
auto rows = topo(rowConditions);
auto cols = topo(colConditions);
if (rows.empty() || cols.empty()) return {};
vector<int> rPos(k + 1), cPos(k + 1);
for (int i = 0; i < k; ++i) { rPos[rows[i]] = i; cPos[cols[i]] = i; }
vector<vector<int>> mat(k, vector<int>(k, 0));
for (int v = 1; v <= k; ++v) mat[rPos[v]][cPos[v]] = v;
return mat;
}
};

Editorial#

Row and column constraints are independent — neither involves the other dimension. Two topological sorts give consistent orders per axis; combined they place each value at a unique row × column.

Complexity#

  • Time: O(k²).
  • Space: O(k²).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.