Build a Matrix With Conditions - Topological Sort [JS]

Description 

Solution: Topological Sort

Use topological sort to find the order that each number should appear for both row and column conditions.
If we can't process all nodes in the topological sort, that means we have a cycle and we return an empty matrix.

Time Complexity: O(k^2) 299ms
Space Complexity: O(k) (not including output) 61MB

var buildMatrix = function(k, rowConditions, colConditions) {
  let rowOrder = getOrder(k + 1, rowConditions);
  let colOrder = getOrder(k + 1, colConditions);
  if (rowOrder === -1 || colOrder === -1) return [];
  let matrix = Array(k).fill(0).map(() => Array(k).fill(0));
  let pos = Array(k + 1).fill(0).map(() => Array(2));
  for (let i = 0; i < k; i++) {
    pos[rowOrder[i]][0] = i;
    pos[colOrder[i]][1] = i;
  }
  for (let i = 1; i <= k; i++) {
    let [x, y] = pos[i];
    matrix[x][y] = i;
  }
  return matrix;
};

function getOrder(n, edges) {
  let indegrees = Array(n).fill(0);
  let graph = Array(n).fill(0).map(() => []);
  for (let [x, y] of edges) {
    graph[x].push(y);
    indegrees[y]++;
  }
  let queue = [];
  for (let i = 1; i < n; i++) {
    if (indegrees[i] === 0) queue.push(i);
  }

  let order = [];
  while (queue.length) {
    let node = queue.shift();
    order.push(node);
    for (let nei of graph[node]) {
      if (--indegrees[nei] === 0) queue.push(nei);
    }
  }
  return order.length === n - 1 ? order : -1;
}

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]