Problem
Given an m x n
picture
consisting of black 'B'
and white 'W'
pixels and an integer target, return the number ofblack lonely pixels.
A black lonely pixel is a character 'B'
that located at a specific position
(r, c)
where:
- Row
r
and columnc
both contain exactlytarget
black pixels. - For all rows that have a black pixel at column
c
, they should be exactly the same as rowr
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
m == picture.length
n == picture[i].length
1 <= m, n <= 200
picture[i][j]
is'W'
or'B'
.1 <= target <= min(m, n)
Solution
Method 1 – Hashing and Row Pattern Counting (1)
Intuition
A black pixel at (r, c) is lonely if both its row and column have exactly target
black pixels, and all rows with a black pixel in column c are identical to row r. We can use hashing to count row patterns and check columns efficiently.
Approach
- For each row, count the number of ‘B’s and store the row as a string pattern.
- For each column, count the number of ‘B’s and record which rows have a ‘B’ in that column.
- For each row pattern that appears exactly
target
times, for each column where that row has a ‘B’, check if:- The column has exactly
target
‘B’s. - All rows with a ‘B’ in that column match the current row pattern.
- The column has exactly
- For each such valid (row, col), add
target
to the answer (since each such column will contributetarget
lonely pixels).
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(mn^2)
, where m and n are the dimensions of the matrix. For each row and column, we may scan all rows. - 🧺 Space complexity:
O(mn)
, for storing row patterns and counts.