Skip to content

Commit 13ca268

Browse files
hashmap for O{1) lookup, maintain row and col arrays for count of uncolored numbers
2661. First Completely Painted Row or Column Solved Medium Topics Companies Hint You are given a 0-indexed integer array arr, and an m x n integer matrix mat. arr and mat both contain all the integers in the range [1, m * n]. Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i]. Return the smallest index i at which either a row or a column will be completely painted in mat. Example 1: image explanation for example 1 Input: arr = [1,3,4,2], mat = [[1,4],[2,3]] Output: 2 Explanation: The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. Example 2: image explanation for example 2 Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] Output: 3 Explanation: The second column becomes fully painted at arr[3]. Constraints: m == mat.length n = mat[i].length arr.length == m * n 1 <= m, n <= 105 1 <= m * n <= 105 1 <= arr[i], mat[r][c] <= m * n All the integers of arr are unique. All the integers of mat are unique. Seen this question in a real interview before? 1/5 Yes No Accepted 77.1K Submissions 126.7K Acceptance Rate 60.8% Topics Array Hash Table Matrix Companies Hint 1 Can we use a frequency array? Hint 2 Pre-process the positions of the values in the matrix. Hint 3 Traverse the array and increment the corresponding row and column frequency using the pre-processed positions. Hint 4 If the row frequency becomes equal to the number of columns, or vice-versa return the current index.
1 parent c8159de commit 13ca268

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public int firstCompleteIndex(int[] arr, int[][] mat) {
3+
int row=mat.length;
4+
int col=mat[0].length;
5+
Map<Integer,int[]> map=new HashMap<>();
6+
for(int i=0;i<row;i++){
7+
for(int j=0;j<col;j++){
8+
map.put(mat[i][j],new int[]{i,j});
9+
}
10+
}
11+
int[] rowcount=new int[row];
12+
int[] colcount=new int[col];
13+
Arrays.fill(rowcount,col);
14+
Arrays.fill(colcount,row);
15+
16+
for(int i=0;i<arr.length;i++){
17+
int[] pos=map.get(arr[i]);
18+
if(--rowcount[pos[0]]==0 || --colcount[pos[1]]==0) return i;
19+
}
20+
return -1;
21+
}
22+
}
23+
24+
25+
26+
/*
27+
mat = [[3,2,5],[1,4,6],[8,7,9]]
28+
29+
arr = [2,8,7,4,1,3,5,6,9],
30+
0 1 2 3 4 5 6 7 8
31+
32+
first three computed normally
33+
2 done
34+
8 done
35+
7 done
36+
37+
check now onwards if on computing any row or coloumn
38+
is formed
39+
40+
41+
42+
43+
44+
45+
46+
47+
*/

0 commit comments

Comments
 (0)