1
+ // 2661. First Completely Painted Row or Column
2
+
3
+ // 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].
4
+
5
+ // Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i].
6
+
7
+ // Return the smallest index i at which either a row or a column will be completely painted in mat.
8
+
9
+ // Example 1:
10
+
11
+ // image explanation for example 1
12
+ // Input: arr = [1,3,4,2], mat = [[1,4],[2,3]]
13
+ // Output: 2
14
+ // Explanation: The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].
15
+ // Example 2:
16
+
17
+ // image explanation for example 2
18
+ // Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]
19
+ // Output: 3
20
+ // Explanation: The second column becomes fully painted at arr[3].
21
+
22
+
23
+ // Constraints:
24
+
25
+ // m == mat.length
26
+ // n = mat[i].length
27
+ // arr.length == m * n
28
+ // 1 <= m, n <= 105
29
+ // 1 <= m * n <= 105
30
+ // 1 <= arr[i], mat[r][c] <= m * n
31
+ // All the integers of arr are unique.
32
+ // All the integers of mat are unique.
33
+
34
+ class Solution
35
+ {
36
+ public:
37
+ int firstCompleteIndex (vector<int > &arr, vector<vector<int >> &mat)
38
+ {
39
+ int rows = mat.size (), cols = mat[0 ].size ();
40
+ unordered_map<int , pair<int , int >> positionMap;
41
+ vector<int > rowCount (rows, cols), colCount (cols, rows);
42
+
43
+ for (int r = 0 ; r < rows; ++r)
44
+ {
45
+ for (int c = 0 ; c < cols; ++c)
46
+ {
47
+ positionMap[mat[r][c]] = {r, c};
48
+ }
49
+ }
50
+
51
+ for (int idx = 0 ; idx < arr.size (); ++idx)
52
+ {
53
+ int val = arr[idx];
54
+ auto [row, col] = positionMap[val];
55
+
56
+ if (--rowCount[row] == 0 || --colCount[col] == 0 )
57
+ {
58
+ return idx;
59
+ }
60
+ }
61
+
62
+ return -1 ;
63
+ }
64
+ };
65
+
66
+ /*
67
+ This code solves the problem of finding the first completely painted row or column in a matrix. Here's how it works:
68
+
69
+ 1. First, it creates a position map that stores the row and column coordinates for each number in the matrix.
70
+
71
+ 2. It initializes two counters:
72
+ - rowCount: tracks remaining unpainted cells in each row (initialized to number of columns)
73
+ - colCount: tracks remaining unpainted cells in each column (initialized to number of rows)
74
+
75
+ 3. For each number in the input array 'arr':
76
+ - Finds its position in the matrix using positionMap
77
+ - Decrements the count for that number's row and column
78
+ - If either count reaches zero, returns the current index
79
+
80
+ 4. Returns -1 if no row or column is completely painted (though this case won't occur given the problem constraints)
81
+
82
+ Time Complexity: O(m*n) for building map, O(k) for processing array where k = m*n
83
+ Space Complexity: O(m*n) for the position map and counter arrays
84
+ */
0 commit comments