I started with using a hashmap (position
) to store the mappings. Then to track the progress of painting, I maintained two counting arrays: one to track the number of painted cells in each row (row_count
) and another for each column (col_count
). As I iterated through the array, I used the position
map to identify the cell to paint and incremented the counts for the respective row and column.
As soon as a row or column becomes fully painted, I returned the current index, as this was guaranteed to be the earliest instance.
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
position = {}
m, n = len(mat), len(mat[0])
for i in range(m):
for j in range(n):
position[mat[i][j]] = (i, j)
row_count = [0] * m
col_count = [0] * n
for index, num in enumerate(arr):
i, j = position[num]
row_count[i] += 1
col_count[j] += 1
if row_count[i] == n or col_count[j] == m:
return index
return -1
- Time: O(m * n)
- Space: O(m * n)
