Lonely Pixel II

The problem is asking us to find the number of “lonely” black pixels in a given picture. A black pixel is considered lonely if:

  • The row and column containing that pixel both have exactly target black pixels.
  • For all rows that have a black pixel at the corresponding column, they should be exactly the same as the row containing the lonely pixel.

Here’s a Python class implementation for this problem:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from collections import defaultdict

class Solution:
    def findBlackPixel(self, picture: List[List[str]], target: int) -> int:
        if not picture or not picture[0]:
            return 0
        
        m, n = len(picture), len(picture[0])
        row_count = [0] * m
        col_count = [0] * n
        rows = defaultdict(int)
        
        for i in range(m):
            for j in range(n):
                if picture[i][j] == 'B':
                    row_count[i] += 1
                    col_count[j] += 1
                    
            row_str = ''.join(picture[i])
            rows[row_str] += 1
        
        result = 0
        
        for i in range(m):
            row_str = ''.join(picture[i])
            if row_count[i] == target and rows[row_str] == target:
                for j in range(n):
                    if picture[i][j] == 'B' and col_count[j] == target:
                        result += 1
                        
        return result

This solution first calculates the counts of black pixels in each row and each column. It then checks the criteria for lonely pixels and adds to the result accordingly. The time complexity is (O(m \times n)), and the space complexity is also (O(m \times n)).