First Completely Painted Row or Column — LeetCode 2661 Python Solution

MediumArrayHash TableMatrix
Problem
#2661
Reading time
3 min

The 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].

Example

Input
arr = [1,3,4,2], mat = [[1,4],[2,3]]
Output
2
Explanation
The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].

Python solution

Python
class Solution:
    def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
        m, n = len(mat), len(mat[0])
        idx = {}
        for i in range(m):
            for j in range(n):
                idx[mat[i][j]] = (i, j)
        row = [0] * m
        col = [0] * n
        for k in range(len(arr)):
            i, j = idx[arr[k]]
            row[i] += 1
            col[j] += 1
            if row[i] == n or col[j] == m:
                return k

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2661. First Completely Painted Row or Column is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2661. First Completely Painted Row or Column?
LeetCode 2661. First Completely Painted Row or Column is rated Medium on LeetCode.
What is the time complexity of LeetCode 2661. First Completely Painted Row or Column?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 2661. First Completely Painted Row or Column?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 2661. First Completely Painted Row or Column cover?
LeetCode 2661. First Completely Painted Row or Column is tagged Array, Hash Table and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview