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
๐Ÿ๏ธ Finding Hermit Pixels in the Matrix OceanMatrix Grid (Islands & Shipping Lanes)๐Ÿ๏ธ๐Ÿง๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿง๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿง๐Ÿ๏ธ๐Ÿง๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿ๏ธRow 0: 2 peopleRow 1: 1 personRow 2: 1 personCol 0: 1Col 1: 1Col 2: 0Col 3: 1Col 4: 1๐ŸŽฏ Hermit Analysisโœ… (1,3): Row=1, Col=1 โ†’ HERMIT!โœ… (2,0): Row=1, Col=1 โ†’ HERMIT!โŒ (0,1): Row=2, Col=1 โ†’ NOT HERMITโŒ (0,4): Row=2, Col=1 โ†’ NOT HERMIT๐Ÿ๏ธ Blue = Empty Island (W) | ๐Ÿง Red = Person on Island (B)A hermit must be alone on their island (row) AND alone in their shipping lane (column)
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!
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 15
38.5K Views
Medium Frequency
~12 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen