Lonely Pixel I - Problem
Imagine you're analyzing a black and white photograph represented as a grid of pixels. Your task is to find all the "lonely black pixels" - those special black pixels that are completely isolated in their row and column.
Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of lonely black pixels.
A lonely black pixel is a black pixel 'B' that satisfies both conditions:
- It's the only black pixel in its entire row
- It's the only black pixel in its entire column
Example: In a 3x3 grid, if there's a black pixel at position (1,1) and it's the only black pixel in row 1 and column 1, then it's considered lonely.
Input & Output
example_1.py โ Basic Case
$
Input:
picture = [['W','W','B'],['W','B','W'],['B','W','W']]
โบ
Output:
3
๐ก Note:
All three black pixels are lonely: (0,2) is alone in row 0 and column 2, (1,1) is alone in row 1 and column 1, (2,0) is alone in row 2 and column 0.
example_2.py โ No Lonely Pixels
$
Input:
picture = [['B','B','B'],['B','B','B']]
โบ
Output:
0
๐ก Note:
No black pixels are lonely because every row and column contains multiple black pixels.
example_3.py โ Mixed Case
$
Input:
picture = [['B','W','W'],['W','W','W'],['W','W','B']]
โบ
Output:
2
๐ก Note:
Both black pixels (0,0) and (2,2) are lonely as they are the only black pixels in their respective rows and columns.
Constraints
- m == picture.length
- n == picture[i].length
- 1 โค m, n โค 500
- picture[i][j] is either 'W' or 'B'
Visualization
Tap to expand
Understanding the Visualization
1
Population Survey
Count how many people live on each island (row) and use each shipping lane (column)
2
Hermit Detection
For each person, check if they're the only one on their island AND the only one in their lane
3
True Hermit
If both conditions are met, we've found a lonely pixel hermit!
Key Takeaway
๐ฏ Key Insight: Pre-counting eliminates redundant scans. Instead of checking each pixel's entire row/column repeatedly, we count once and lookup in O(1) time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code