Lonely Pixel II - Problem
Imagine you're analyzing a digital image represented as a matrix of black ('B') and white ('W') pixels. Your task is to find lonely black pixels - special black pixels that meet very specific criteria!
A black lonely pixel is a 'B' located at position (r, c) where:
- Both row
rand columnccontain exactlytargetblack pixels - All rows that have a black pixel at column
cmust be identical to rowr
Goal: Count how many black lonely pixels exist in the given m ร n picture.
Example: If target = 3, a black pixel is lonely only if its row and column both have exactly 3 black pixels, and any other rows with black pixels in the same column are identical to this row.
Input & Output
example_1.py โ Basic Case
$
Input:
picture = [["W","B","W","B","B","W"],["W","B","W","B","B","W"],["W","B","W","B","B","W"],["W","W","B","W","B","B"]], target = 3
โบ
Output:
6
๐ก Note:
The first three rows are identical and each has 3 black pixels. For columns 1, 3, 4: each has exactly 3 black pixels and all blacks in these columns come from identical rows. Each black pixel in these positions is lonely, giving us 3 rows ร 3 columns = 6 lonely pixels.
example_2.py โ No Lonely Pixels
$
Input:
picture = [["W","W","B"],["W","W","B"],["W","W","B"]], target = 1
โบ
Output:
0
๐ก Note:
Column 2 has 3 black pixels, but target is 1, so no black pixel can be lonely. Even though each row has exactly 1 black pixel, the column condition fails.
example_3.py โ Different Row Patterns
$
Input:
picture = [["B","W"],["W","B"]], target = 1
โบ
Output:
0
๐ก Note:
Each row and column has exactly 1 black pixel, but the rows with black pixels in the same column are different (["B","W"] vs ["W","B"]), so no pixels are lonely.
Constraints
- m == picture.length
- n == picture[i].length
- 1 โค m, n โค 200
- picture[i][j] is either 'W' or 'B'
- 1 โค target โค min(m, n)
Visualization
Tap to expand
Understanding the Visualization
1
Group Identical Patterns
Use hash map to group rows with identical camera arrangements
2
Filter Valid Groups
Keep only groups where each row has exactly target cameras
3
Column Analysis
For each column position with cameras, count total cameras in that column
4
Validate Consistency
Ensure all cameras in a column come from the same row pattern
5
Count Lonely Cameras
Sum up all valid cameras meeting all conditions
Key Takeaway
๐ฏ Key Insight: Using hash map to group identical row patterns eliminates redundant comparisons and enables O(mn) solution by validating row consistency efficiently.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code