Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created January 20, 2025 22:54
Show Gist options
  • Save Ifihan/a24ac3e64e1d35abc3fa1c6567f8715f to your computer and use it in GitHub Desktop.
Save Ifihan/a24ac3e64e1d35abc3fa1c6567f8715f to your computer and use it in GitHub Desktop.
First Completely Painted Row or Column

Question

Approach

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.

Implementation

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 

Complexities

  • Time: O(m * n)
  • Space: O(m * n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment