2661. First Completely Painted Row or Column
Explanation
To solve this problem, we will iterate through the elements in the arr
array and keep track of how many cells have been painted in each row and each column. We will use two arrays, rows
and cols
, to store the number of painted cells in each row and each column respectively. Additionally, we will use two sets, paintedRows
and paintedCols
, to store the rows and columns that are completely painted.
As we iterate through the arr
array, we will increment the count of painted cells in the corresponding row and column. If the count reaches the total number of cells in a row or a column, we will add that row or column to the respective set of completely painted rows or columns. We will return the index at which either a row or a column is completely painted first.
Time complexity: O(m*n) where m is the number of rows and n is the number of columns in the matrix. Space complexity: O(m + n) for the row and column arrays.
class Solution {
public int paintMatrix(int[] arr, int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[] rows = new int[m];
int[] cols = new int[n];
Set<Integer> paintedRows = new HashSet<>();
Set<Integer> paintedCols = new HashSet();
for (int i = 0; i < arr.length; i++) {
int num = arr[i];
int r = (num - 1) / n;
int c = (num - 1) % n;
rows[r]++;
cols[c]++;
if (rows[r] == n) paintedRows.add(r);
if (cols[c] == m) paintedCols.add(c);
if (paintedRows.contains(r) || paintedCols.contains(c)) {
return i + 1;
}
}
return -1;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.