Lonely Pixel I - Problem

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 is located at a specific position where the same row and same column don't have any other black pixels.

Input & Output

Example 1 — Basic Case
$ Input: picture = [["W","W","B"],["W","B","W"],["W","W","B"]]
Output: 1
💡 Note: Only the black pixel at (1,1) is lonely. Row 1 has 1 black pixel, column 1 has 1 black pixel. The other black pixels have companions in their rows or columns.
Example 2 — No Lonely Pixels
$ Input: picture = [["B","B"],["B","W"]]
Output: 0
💡 Note: No lonely pixels exist. The black pixel at (0,0) shares row 0 with (0,1), pixel at (0,1) shares both row 0 and column 1, and pixel at (1,0) shares column 0.
Example 3 — Single Black Pixel
$ Input: picture = [["W","W"],["W","B"]]
Output: 1
💡 Note: The single black pixel at (1,1) is lonely since it's the only black pixel in both row 1 and column 1.

Constraints

  • m == picture.length
  • n == picture[i].length
  • 1 ≤ m, n ≤ 500
  • picture[i][j] is either 'W' or 'B'

Visualization

Tap to expand
Lonely Pixel I - Finding Isolated Black Pixels INPUT m x n Picture Grid (3x3) W W B W B W W W B 0 1 2 0 1 2 [["W","W","B"], ["W","B","W"], ["W","W","B"]] 3 Black pixels to check B at: (0,2), (1,1), (2,2) Goal: Find lonely pixels ALGORITHM STEPS 1 Count B in each row rowCount = [1, 1, 1] 2 Count B in each col colCount = [0, 1, 2] 3 Check each B pixel If row=1 AND col=1 4 Count lonely pixels Increment if both = 1 Pixel Analysis (0,2): row[0]=1, col[2]=2 NOT lonely (1,1): row[1]=1, col[1]=1 LONELY! (2,2): row[2]=1, col[2]=2 NOT lonely Time: O(m*n) | Space: O(m+n) Two passes through grid Optimal linear solution FINAL RESULT Lonely Pixel Highlighted W W B W B W W W B Lonely (counted) Not lonely (col=2) Output: 1 Only (1,1) is lonely! Key Insight: A black pixel is "lonely" only when it's the ONLY black pixel in both its row AND column. Pre-computing row and column counts lets us check each pixel in O(1) time instead of O(m+n). At position (1,1): rowCount[1]=1 and colCount[1]=1, so it's the only lonely pixel. Column 2 has 2 black pixels! TutorialsPoint - Lonely Pixel I | Optimal Solution O(m*n)
Asked in
Google 15 Facebook 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
245 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