#2661

First Completely Painted Row or Column

Medium
ArrayHash TableMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a mapping of values to their positions in the matrix, allowing us to efficiently track painted cells and check for complete rows or columns without repeatedly scanning the matrix.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a mapping of each value in mat to its coordinates.
  2. 2Step 2: Initialize counters for rows and columns to track painted counts.
  3. 3Step 3: For each index in arr, use the mapping to find the position and update the counters.
  4. 4Step 4: After each update, check if any row or column has been fully painted.
solution.py14 lines
1# Full working Python code
2class Solution:
3    def firstCompleteIndex(self, arr, mat):
4        m, n = len(mat), len(mat[0])
5        position = {mat[r][c]: (r, c) for r in range(m) for c in range(n)}
6        row_count = [0] * m
7        col_count = [0] * n
8        for i, num in enumerate(arr):
9            r, c = position[num]
10            row_count[r] += 1
11            col_count[c] += 1
12            if row_count[r] == n or col_count[c] == m:
13                return i
14        return -1

Complexity note: This complexity is optimal because we only traverse the array and matrix a limited number of times, leading to a linear time complexity.

  • 1Using a mapping allows for quick access to matrix positions, improving efficiency.
  • 2Tracking painted counts for rows and columns can help determine completion without scanning the entire matrix.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.