First Completely Painted Row or Column - Counting [JS]

Description 

Solution: Counting

Map each arr[i] to its row and column in mat.
Keep track of the count of numbers unused in each row and column.
As we go through each arr[i], subtract from the row count and column count and if any count is 0, return i.

Time Complexity: O(mn)
Space Complexity: O(mn)

var firstCompleteIndex = function(arr, mat) {
  let m = mat.length, n = mat[0].length;
  let coordinates = Array(m * n + 1);
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      coordinates[mat[i][j]] = [i, j];
    }
  }
  let rowCount = Array(m).fill(n), colCount = Array(n).fill(m);
  for (let i = 0; i < m * n; i++) {
    let [row, col] = coordinates[arr[i]];
    if (--rowCount[row] === 0 || --colCount[col] === 0) return i; 
  }
};

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]