First Completely Painted Row or Column

Updated on 30 May, 2025
First Completely Painted Row or Column header image

Problem Statement

In this problem, you are given two main data structures:

  • A zero-indexed integer array named arr.
  • An integer matrix mat with dimensions m x n.

Both arr and mat include every integer from the range [1, m * n] exactly once. The task is to simulate a painting process where we sequentially take elements from the array arr and use each element to paint the corresponding cell in the matrix mat where that integer is located.

The objective is to determine the smallest array index i such that, by the time we reach arr[i], there is at least one entire row or column in mat that has been completely painted. You must develop an approach to find this index i efficiently given the constraints of the problem.

Examples

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

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.

Approach and Intuition

To solve this problem, follow these logical steps:

  1. First, realize the need for keeping track of the paint status of each row and column in the matrix mat.

    • Create counters for each row and each column to count how many cells in each row and column have been painted so far.
  2. Determine the position of each integer in the matrix mat initially to avoid searching for its position every time. This can be done by creating a mapping from the integer value to its row and column indices in mat.

    • For example, create a dictionary position_map where position_map[val] gives (row, column).
  3. Start processing each element in the array arr sequentially from index 0. For each element:

    • Use the previously built position_map to find out in which row and column the current element is located.
    • Increment the paint counters for the respective row and column.
    • After updating the counters, check if any of the counters for the current row or column has reached the total number of cells in its respective row or column, which means it is fully painted.
  4. Return the index i when you first encounter a fully painted row or column.

To summarize:

By maintaining a two-dimensional mapping of value positions and using direct increment counters for rows and columns, the solution efficiently keeps track of progress with each marble placed. The problem is thus reduced to looking up and updating counters efficiently, resulting in a solution that works well within the given constraints.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int findFirstFullIndex(vector<int>& nums, vector<vector<int>>& grid) {
        unordered_map<int, int> valueToPosition;
        for (int idx = 0; idx < nums.size(); idx++) {
            valueToPosition[nums[idx]] = idx;
        }

        int minIndex = INT_MAX;
        int rowCount = grid.size();
        int colCount = grid[0].size();

        for (int r = 0; r < rowCount; r++) {
            int maxIndexInRow = INT_MIN;
            for (int c = 0; c < colCount; c++) {
                int mappedIndex = valueToPosition[grid[r][c]];
                maxIndexInRow = max(maxIndexInRow, mappedIndex);
            }
            minIndex = min(minIndex, maxIndexInRow);
        }

        for (int c = 0; c < colCount; c++) {
            int maxIndexInCol = INT_MIN;
            for (int r = 0; r < rowCount; r++) {
                int mappedIndex = valueToPosition[grid[r][c]];
                maxIndexInCol = max(maxIndexInCol, mappedIndex);
            }
            minIndex = min(minIndex, maxIndexInCol);
        }

        return minIndex;
    }
};

The provided C++ solution effectively finds the first completely painted row or column in a given grid, using a provided mapping list nums. This approach ensures that the solution is able to determine which row or column is painted first based on a predefined order.

Here's a concise explanation of how the solution operates:

  • Initializes a dictionary valueToPosition to keep track of the position each value from nums corresponds to, utilizing their index.
  • Initializes minIndex to INT_MAX to find the minimum index of fully painted rows or columns.
  • Iterates through each row to find the maximum index in the row based on the values from nums.
  • Updates minIndex to be the minimum between the previous minIndex and the maximum index found in the current row.
  • Similarly, iterates through each column to find the maximum index in the column using the same mapping, and updates minIndex accordingly.
  • Returns minIndex, which corresponds to the smallest index of fully painted rows or columns as per the mapping defined by nums.

This method provides an efficient way to evaluate a grid by leveraging space for mapping and time for iterating over the grid rows and columns only once each.

java
class Solution {

    public int completeIndex(int[] array, int[][] matrix) {
        // Store mapping of elements to their indices from array
        Map<Integer, Integer> elementIndexMap = new HashMap<>();
        for (int idx = 0; idx < array.length; idx++) {
            elementIndexMap.put(array[idx], idx);
        }

        int minIndex = Integer.MAX_VALUE;
        int maxRows = matrix.length;
        int maxCols = matrix[0].length;

        // Determine earliest row index with all elements present
        for (int r = 0; r < maxRows; r++) {
            int highestIdxInRow = Integer.MIN_VALUE;
            for (int c = 0; c < maxCols; c++) {
                int currentIdx = elementIndexMap.get(matrix[r][c]);
                highestIdxInRow = Math.max(highestIdxInRow, currentIdx);
            }
            minIndex = Math.min(minIndex, highestIdxInRow);
        }

        // Determine earliest column index with all elements present
        for (int c = 0; c < maxCols; c++) {
            int highestIdxInCol = Integer.MIN_VALUE;
            for (int r = 0; r < maxRows; r++) {
                int currentIdx = elementIndexMap.get(matrix[r][c]);
                highestIdxInCol = Math.max(highestIdxInCol, currentIdx);
            }
            minIndex = Math.min(minIndex, highestIdxInCol);
        }

        return minIndex;
    }
}

The provided Java program, Solution, includes a method completeIndex that identifies the earliest index in an array where all elements are completely present in any row or column of a matrix. The method uses a mapping strategy combined with iteration over matrix rows and columns to accomplish this.

  • The completeIndex method starts by creating a HashMap (elementIndexMap) which maps each element in the given array to its index. This facilitates quick lookup of positions while scanning the matrix.

  • Next, the function initializes minIndex with Integer.MAX_VALUE to keep track of the smallest index where a row or column is completely painted or filled.

  • The method uses two nested loops to process each row of the matrix. In the inner loop for each row, it determines the maximum index of elements as present in the elementIndexMap. The minimum index among all rows is updated in minIndex.

  • Similarly, another set of nested loops calculates the earliest completely painted column, updating minIndex in case a smaller index is found.

  • After processing both rows and columns, the completeIndex method returns minIndex. If minIndex remains Integer.MAX_VALUE, it indicates that no row or column is fully covered by the elements of the array.

This approach ensures an efficient algorithm to find the first completely painted row or column by leveraging direct access data structures and iterative comparison.

python
class Solution:
    def completePaintIndex(self, sequence, grid):
        index_map = {}
        for index in range(len(sequence)):
            index_map[sequence[index]] = index

        earliest_full = float("inf")
        total_rows, total_cols = len(grid), len(grid[0])

        for r in range(total_rows):
            max_index_in_row = float("-inf")
            for c in range(total_cols):
                current_index = index_map[grid[r][c]]
                max_index_in_row = max(max_index_in_row, current_index)

            earliest_full = min(earliest_full, max_index_in_row)

        for c in range(total_cols):
            max_index_in_col = float("-inf")
            for r in range(total_rows):
                current_index = index_map[grid[r][c]]
                max_index_in_col = max(max_index_in_col, current_index)

            earliest_full = min(earliest_full, max_index_in_col)

        return earliest_full

This Python solution determines the first row or column in a grid that is completely painted based on a sequence of painting actions. The implemented approach efficiently finds out which row or column is fully painted first, using the following strategy:

  • Establish a mapping from grid values (colors or identifiers) to their respective indices in the sequence array. This mapping indicates the order in which each color appears.
  • Using two separate loops, compute the max sequence index for each row and column. Track the maximum sequence index encountered in each row and each column to identify the last paint action affecting it.
  • Determine the minimum value from these maximum sequence indices to find the earliest painted row or column.
  • The result will be the earliest sequence index at which a row or column is fully painted.

This involves iterating over each row and column, which ensures that all scenarios are checked. The solution efficiently compares sequence indices to determine the earliest point a row or column becomes fully painted, optimizing the process by focusing on the most essential calculations and comparisons.

Comments

No comments yet.