Lonely Pixel II - Problem

Given an m x n picture consisting of black 'B' and white 'W' pixels and an integer target, return the number of black lonely pixels.

A black lonely pixel is a character 'B' that located at a specific position (r, c) where:

  • Row r and column c both contain exactly target black pixels.
  • For all rows that have a black pixel at column c, they should be exactly the same as row r.

Input & Output

Example 1 — Basic Case
$ Input: picture = [["W","B","W","B"],["B","W","B","W"],["B","W","W","W"]], target = 2
Output: 3
💡 Note: Row 0 has 2 black pixels, row 1 has 2 black pixels. Column 0 has 2 black pixels, column 2 has 1 black pixel. For pixels at (0,1) and (1,2): their columns don't have target count. For pixels at (0,0), (1,0), (0,3): column 0 has 2 black pixels and rows 0,1 are different patterns, so no lonely pixels. Actually, let me recalculate: Position (1,0) in row 1 with 2 B's, column 0 with 2 B's, but rows 1 and 2 both have B in column 0 and are different.
Example 2 — Identical Rows
$ Input: picture = [["W","B"],["W","B"]], target = 1
Output: 2
💡 Note: Both rows are identical "WB" and each has 1 black pixel. Column 1 has 2 black pixels total, but we need exactly target=1, so no lonely pixels. Wait, let me recalculate: Column 1 has 2 B's but target is 1, so condition fails.
Example 3 — Single Row Match
$ Input: picture = [["B","B"],["W","W"]], target = 2
Output: 2
💡 Note: Row 0 has 2 black pixels (matches target). Column 0 has 1 black pixel, column 1 has 1 black pixel. Neither column has target=2 black pixels, so no lonely pixels.

Constraints

  • m == picture.length
  • n == picture[i].length
  • 1 ≤ m, n ≤ 200
  • picture[i][j] is 'W' or 'B'
  • 1 ≤ target ≤ min(m, n)

Visualization

Tap to expand
INPUT MATRIXCONDITION CHECKFINAL RESULTWBWBBWBWBWWWTarget = 2Find black pixels where:• Row has exactly 2 B pixels• Column has exactly 2 B pixels• All rows in column identical1Count row/column pixels2Group identical rows3Check target conditions4Verify row patterns matchEfficient O(mn) algorithmusing hash maps forgrouping identical rowsLonely Pixels3Black pixels at positionsmeeting all three conditions:• Correct row count• Correct column count• Identical row patternsKey Insight:Group identical rows together to avoid redundant comparisons.Use hash maps to efficiently check all three lonely pixel conditions.TutorialsPoint - Lonely Pixel II | Hash Map Optimization
Asked in
Google 25 Facebook 18 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
456 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