Lonely Pixel I Problem
Description
LeetCode Problem 531.
Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels.
A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.
Example 1:
![]()
Input: picture = [["W","W","B"],["W","B","W"],["B","W","W"]]
Output: 3
Explanation: All the three 'B's are black lonely pixels.
Example 2:
![]()
Input: picture = [["B","B","B"],["B","B","W"],["B","B","B"]]
Output: 0
Constraints:
m == picture.lengthn == picture[i].length1 <= m, n <= 500picture[i][j]is'W'or'B'.
Solution
Approach: Count Each Row and Column
A black pixel is lonely when it is the only black pixel in its row and the only one in its column. Checking the whole row and column for every black pixel would cost O(m + n) per pixel, but we can count once and reuse the counts.
- First pass: for every
'B'at(i, j), add one torows[i]and tocols[j]. - Second pass: a
'B'at(i, j)is lonely exactly whenrows[i] == 1andcols[j] == 1. Count those.
The pixel itself is included in both counts, so "no other black pixel" means a count of exactly 1, not 0. In Example 2, every row and column has at least two black pixels, so the answer is 0.
Complexity: O(mn) time for two passes over the picture. O(m + n) extra space for the counts.
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int:
rows = [0] * len(picture) # black pixels in each row
cols = [0] * len(picture[0]) # black pixels in each column
for i, row in enumerate(picture):
for j, x in enumerate(row):
if x == "B":
rows[i] += 1
cols[j] += 1
return sum(
x == "B" and rows[i] == 1 and cols[j] == 1
for i, row in enumerate(picture)
for j, x in enumerate(row)
)