LeetCode 2661. First Completely Painted Row or Column Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2661. First Completely Painted Row or Column

Description

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

Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i].

Return the smallest index i at which either a row or a column will be completely painted in mat.

 

Example 1:

https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1
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].

Example 2:

image explanation for example 2
Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]
Output: 3
Explanation: The second column becomes fully painted at arr[3].

 

Constraints:

  • m == mat.length
  • n = mat[i].length
  • arr.length == m * n
  • 1 <= m, n <= 105
  • 1 <= m * n <= 105
  • 1 <= arr[i], mat[r][c] <= m * n
  • All the integers of arr are unique.
  • All the integers of mat are unique.

Solutions

Solution 1: Hash Table + Array Counting

We use a hash table idx to record the position of each element in the matrix mat, that is idx[mat[i][j]] = (i, j), and define two arrays row and col to record the number of colored elements in each row and each column respectively.

Traverse the array arr. For each element arr[k], we find its position (i, j) in the matrix mat, and then add row[i] and col[j] by one. If row[i] = n or col[j] = m, it means that the i-th row or the j-th column has been colored, so arr[k] is the element we are looking for, and we return k.

The time complexity is O(m × n), and the space complexity is O(m × n). Here m and n are the number of rows and columns of the matrix mat respectively.

PythonJavaC++GoTypeScriptRust
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !