LeetCode 2661: First Completely Painted Row or Column Solution

Master LeetCode problem 2661 (First Completely Painted Row or Column), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2661. First Completely Painted Row or Column

Problem Explanation

Explanation

To solve this problem, we will iterate through the elements in the arr array and keep track of how many cells have been painted in each row and each column. We will use two arrays, rows and cols, to store the number of painted cells in each row and each column respectively. Additionally, we will use two sets, paintedRows and paintedCols, to store the rows and columns that are completely painted.

As we iterate through the arr array, we will increment the count of painted cells in the corresponding row and column. If the count reaches the total number of cells in a row or a column, we will add that row or column to the respective set of completely painted rows or columns. We will return the index at which either a row or a column is completely painted first.

Time complexity: O(m*n) where m is the number of rows and n is the number of columns in the matrix. Space complexity: O(m + n) for the row and column arrays.

Solution Code

class Solution {
    public int paintMatrix(int[] arr, int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int[] rows = new int[m];
        int[] cols = new int[n];
        Set<Integer> paintedRows = new HashSet<>();
        Set<Integer> paintedCols = new HashSet();

        for (int i = 0; i < arr.length; i++) {
            int num = arr[i];
            int r = (num - 1) / n;
            int c = (num - 1) % n;
            rows[r]++;
            cols[c]++;
            if (rows[r] == n) paintedRows.add(r);
            if (cols[c] == m) paintedCols.add(c);
            if (paintedRows.contains(r) || paintedCols.contains(c)) {
                return i + 1;
            }
        }
        
        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2661 (First Completely Painted Row or Column)?

This page provides optimized solutions for LeetCode problem 2661 (First Completely Painted Row or Column) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2661 (First Completely Painted Row or Column)?

The time complexity for LeetCode 2661 (First Completely Painted Row or Column) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2661 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2661 in Java, C++, or Python.

Back to LeetCode Solutions