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.

531. Lonely Pixel I

ArrayHash TableMatrix

Explanation

The problem asks us to find the number of lonely pixels in a black-and-white image. A lonely pixel is defined as a black pixel (represented by 'B') that is the only one in its row and column.

To solve this problem, we can iterate through the image and count the number of black pixels in each row and column. Then, we iterate through the image again and check if a black pixel is the only one in its row and column. If it is, we increment a counter for lonely pixels.

Algorithm:

  1. Initialize arrays rowCount and colCount to store counts of black pixels in each row and column, respectively.
  2. Iterate through the image to count black pixels in each row and column and store the counts in rowCount and colCount.
  3. Iterate through the image again and for each black pixel, check if it is the only one in its row and column. If so, increment the counter for lonely pixels.
  4. Return the count of lonely pixels.

Time Complexity:

  • O(m * n) where m and n are the number of rows and columns in the image.

Space Complexity:

  • O(m + n) for the rowCount and colCount arrays.
class Solution {
    public int findLonelyPixel(char[][] picture) {
        int m = picture.length, n = picture[0].length;
        int[] rowCount = new int[m];
        int[] colCount = new int[n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (picture[i][j] == 'B') {
                    rowCount[i]++;
                    colCount[j]++;
                }
            }
        }
        
        int lonelyPixelCount = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (picture[i][j] == 'B' && rowCount[i] == 1 && colCount[j] == 1) {
                    lonelyPixelCount++;
                }
            }
        }
        
        return lonelyPixelCount;
    }
}

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.