MediumNo. 2661

First Completely Painted Row or Column — LeetCode 2661 Python Solution

Topics
Array, Hash Table, Matrix
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

PythonSolution
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

Time
O(m × n)
Space · auxiliary
O(m × n)

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

Related problems
No.ProblemDifficulty
0036Valid SudokuMedium
0037Sudoku SolverHard
0073Set Matrix ZeroesMedium
0840Magic Squares In GridMedium
0959Regions Cut By SlashesMedium
1072Flip Columns For Maximum Number of Equal RowsMedium

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 × n).

What is the space complexity of LeetCode 2661. First Completely Painted Row or Column?

The Python solution on this page uses O(m × 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.

Free to download. Check it runs on your machine, then pick a plan.