Problem Description
Given an m x n matrix (mat) that contains all integers from 1 to mn (with unique entries) and an array (arr) of length mn representing a painting order, we need to paint cells in the matrix in the order given by arr. The task is to determine the smallest index i at which an entire row or column in the matrix becomes completely painted.
Key Insights
- Preprocess the matrix to create a mapping from cell values to their (row, col) positions.
- Maintain counters for each row and each column to track the number of painted cells.
- As you process each element in arr, update the corresponding row and column counters.
- Check if a row counter equals the number of columns or if a column counter equals the number of rows. If so, return the current index.
- The algorithm performs a single pass over arr and constant-time operations for each step.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n) for the mapping plus O(m + n) for the counters
Solution
Create a mapping from each matrix value to its coordinates using a dictionary or hash map. Initialize two arrays (or hash maps) to store the count of painted cells in each row and column. Iterate through the array arr:
- For each value, retrieve its (row, col) position from the mapping.
- Increase the corresponding row and column counters.
- Check if the count equals the total number of columns (for the row) or the total number of rows (for the column). If true, return the current index as the answer.
This approach efficiently simulates the painting process while tracking the condition required to complete a row or a column.