Leetcode 2661: First Completely Painted Row or Column

grid47
grid47
Exploring patterns and algorithms
Feb 14, 2024 7 min read

You are given a list of integers arr and a 2D matrix mat. The list arr contains all the integers from the range [1, m * n] and represents the order in which you paint the cells of mat. Each integer in arr corresponds to a cell in mat that is being painted. The goal is to find the smallest index i at which either a row or a column becomes completely painted.
Problem
Approach
Steps
Complexity
Input: The input consists of two elements: an array `arr` and a 2D integer matrix `mat`.
Example: Input: arr = [3, 1, 2, 4], mat = [[4, 1], [3, 2]]
Constraints:
• 1 <= m, n <= 10^5
• 1 <= m * n <= 10^5
• 1 <= arr[i], mat[r][c] <= m * n
• All integers in `arr` are unique.
• All integers in `mat` are unique.
Output: The output should be the smallest index `i` at which either a row or a column is completely painted.
Example: Output: 2
Constraints:
• The output should be a non-negative integer representing the smallest index `i`.
Goal: The goal is to track when a row or column is completely painted by checking each number in `arr` and marking the corresponding cell in `mat`.
Steps:
• Step 1: Create mappings for each value in `mat` to its corresponding row and column index.
• Step 2: Initialize counters for each row and column to keep track of how many cells are painted.
• Step 3: Iterate through the array `arr` and for each number, increment the counters for the corresponding row and column.
• Step 4: Check if any row or column is completely painted. If so, return the index `i`.
Goal: Ensure the solution can efficiently handle the constraints on the input sizes.
Steps:
• The input sizes can be large, so the solution should be optimal with respect to time and space.
Assumptions:
• Each element in `arr` corresponds to a unique position in `mat`.
Input: Input: arr = [3, 1, 2, 4], mat = [[4, 1], [3, 2]]
Explanation: The cells are painted in the order: arr[0] = 3, arr[1] = 1, arr[2] = 2, arr[3] = 4. After arr[2], both the first row and second column are completely painted, so the smallest index is 2.

Input: Input: arr = [8, 5, 1, 7, 3, 4, 2, 6], mat = [[1, 5, 7], [2, 8, 6], [3, 4, 9]]
Explanation: The cells are painted in the order: arr[0] = 8, arr[1] = 5, arr[2] = 1, arr[3] = 7. After arr[3], the second column is completely painted, so the smallest index is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus