Problem
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
.
Examples
Example 1:
$$ \begin{array}{|c|c|} \hline \colorbox{Turquoise} 1 & 4 \\ \hline 2 & 3 \\ \hline \end{array}
\longrightarrow \begin{array}{|c|c|} \hline \colorbox{Turquoise} 1 & 4 \\ \hline 2 & \colorbox{Turquoise} 3 \\ \hline \end{array}
\longrightarrow \begin{array}{|c|c|} \hline \colorbox{Turquoise} 1 & \colorbox{Turquoise} 4 \\ \hline 2 & \colorbox{Turquoise} 3 \\ \hline \end{array} $$
|
|
Example 2:
$$ \begin{array}{|c|c|c|} \hline 3 & \colorbox{Turquoise} 2 & 5 \\ \hline 1 & 4 & 6 \\ \hline 8 & 7 & 9 \\ \hline \end{array}
\longrightarrow \begin{array}{|c|c|c|} \hline 3 & \colorbox{Turquoise} 2 & 5 \\ \hline 1 & 4 & 6 \\ \hline \colorbox{Turquoise} 8 & 7 & 9 \\ \hline \end{array}
\longrightarrow \begin{array}{|c|c|c|} \hline 3 & \colorbox{Turquoise} 2 & 5 \\ \hline 1 & 4 & 6 \\ \hline \colorbox{Turquoise} 8 & \colorbox{Turquoise} 7 & 9 \\ \hline \end{array}
\longrightarrow \begin{array}{|c|c|c|} \hline 3 & \colorbox{Turquoise} 2 & 5 \\ \hline 1 & \colorbox{Turquoise} 4 & 6 \\ \hline \colorbox{Turquoise} 8 & \colorbox{Turquoise} 7 & 9 \\ \hline \end{array} $$
|
|
$$ mat = \begin{array}{|c|c|c|} \hline 3 & 2 & 5 \\ \hline 1 & 4 & 6 \\ \hline 8 & 7 & 9 \\ \hline \end{array} $$
Constraints:
m == mat.length
n = mat[i].length
arr.length == m * n
1 <= m, n <= 10^5
1 <= m * n <= 1^05
1 <= arr[i], mat[r][c] <= m * n
- All the integers of
arr
are unique. - All the integers of
mat
are unique.
Solution
Method 1 - Using Hashtable and Count
To solve this problem, we need to perform the following steps:
- Traverse each element in
arr
and mark the corresponding cell inmat
as painted. - Check after each painting if any complete row or column is fully painted.
- Return the index at which a row or column is completely painted for the first time.
To implement this:
- Use two arrays to track the number of painted cells in each row and each column.
- Utilize a hashmap to store the positions of each number in
mat
for O(1) look-up time. - Iterate through
arr
and update the row and column counters. - Check if any row or column count reaches the respective row or column size after each update.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
because we will iterate through all elements inarr
once, and the look-up and update operations are O(1) each. - 🧺 Space complexity:
O(m * n)
because we are using additional space to store the positions of the numbers and the counters for rows and columns.