Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

533. Lonely Pixel II

ArrayHash TableMatrix

Explanation

The problem "Lonely Pixel II" asks us to determine the number of "black" pixels in a given picture that meet specific criteria. A black pixel is represented as 'B' and a white pixel is represented as 'W'. The criteria for a black pixel to be considered "lonely" are:

  1. There must be exactly one black pixel in the same row as the given black pixel.
  2. There must be exactly one black pixel in the same column as the given black pixel.

To solve this problem efficiently, we can follow these steps:

  1. Count the number of black pixels in each row and each column.
  2. For each black pixel, check if it is lonely based on the above criteria.
  3. Count the total number of lonely black pixels.

Time complexity: O(mn) where m is the number of rows and n is the number of columns in the picture. Space complexity: O(m + n) to store the counts of black pixels in each row and each column.

class Solution {
    public int findBlackPixel(char[][] picture, int N) {
        int m = picture.length;
        int n = picture[0].length;
        int[] rowCount = new int[m];
        int[] colCount = new int[n];
        Map<String, Integer> map = new HashMap<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (picture[i][j] == 'B') {
                    rowCount[i]++;
                    colCount[j]++;
                }
            }
        }

        for (int i = 0; i < m; i++) {
            if (rowCount[i] == N) {
                String key = Arrays.toString(picture[i]);
                map.put(key, map.getOrDefault(key, 0) + 1);
            }
        }

        int count = 0;
        for (int j = 0; j < n; j++) {
            if (colCount[j] == N) {
                for (Map.Entry<String, Integer> entry : map.entrySet()) {
                    if (entry.getValue() == N && entry.getKey().charAt(j) == 'B') {
                        count += N;
                    }
                }
            }
        }

        return count;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.