 "Matrix Painting Completion" || Beats 99.09% Users .
IntuitionThe problem can be approached by tracking the count of painted cells in each row and column. When either a row or a column becomes fully painted, we re
![Screenshot 2025-01-20 194552.png](https://assets.leetcode.com/users/images/cb05c741-fcdb-4ca3-b3bc-4136fc9e1fed_1737382572.4032254.png)
# Intuition
The problem can be approached by tracking the count of painted cells in each row and column. When either a row or a column becomes fully painted, we return the corresponding index from `arr`.

# Approach
1. Map each number in `mat` to its position (row and column) using a vector for efficient lookup.
2. Maintain two arrays:
   - `rowCount` to track the number of painted cells in each row.
   - `colCount` to track the number of painted cells in each column.
3. Iterate through `arr` and for each number:
   - Locate its position in `mat` using the precomputed mapping.
   - Increment the corresponding row and column counts.
   - Check if the current row or column is fully painted.
4. Return the index where a row or column is fully painted.

# Complexity
- **Time complexity**:  
  $$O(m \times n)$$ for preprocessing the mapping and iterating through `arr`.
- **Space complexity**:  
  $$O(m + n)$$ for `rowCount` and `colCount` arrays.

# Code
```cpp []
class Solution {
public:
    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size();
        // Map each number in mat to its position
        vector<pair<int, int>> pos(m * n + 1); // Using 1-based indexing
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                pos[mat[i][j]] = {i, j};
            }
        }
        // Arrays to track painted cells in rows and columns
        vector<int> rowCount(m, 0), colCount(n, 0);
        // Iterate through arr and update row/column counts
        for (int i = 0; i < arr.size(); ++i) {
            auto [r, c] = pos[arr[i]];
            if (++rowCount[r] == n || ++colCount[c] == m) {
                return i; // Return the first index completing a row or column
            }
        }

        return -1; // Should never be reached
    }
};
```
['Hash Table', 'Matrix', 'Simulation', 'C++']