Lonely Pixel I
Problem
Return the number of black ('B') pixels that are alone in their row AND column.
picture = [["W","W","B"],["W","B","W"],["B","W","W"]]3def find_lonely_pixel(picture):
R, C = len(picture), len(picture[0])
row = [sum(1 for c in r if c == "B") for r in picture]
col = [sum(1 for i in range(R) if picture[i][j] == "B") for j in range(C)]
return sum(1 for i in range(R) for j in range(C) if picture[i][j] == "B" and row[i] == 1 and col[j] == 1)
function findLonelyPixel(p) {
const R = p.length, C = p[0].length;
const row = new Array(R).fill(0), col = new Array(C).fill(0);
for (let i = 0; i < R; i++) for (let j = 0; j < C; j++) if (p[i][j] === "B") { row[i]++; col[j]++; }
let n = 0;
for (let i = 0; i < R; i++) for (let j = 0; j < C; j++) if (p[i][j] === "B" && row[i] === 1 && col[j] === 1) n++;
return n;
}
class Solution {
public int findLonelyPixel(char[][] p) {
int R = p.length, C = p[0].length;
int[] row = new int[R], col = new int[C];
for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (p[i][j] == 'B') { row[i]++; col[j]++; }
int n = 0;
for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (p[i][j] == 'B' && row[i] == 1 && col[j] == 1) n++;
return n;
}
}
int findLonelyPixel(vector>& p) {
int R = p.size(), C = p[0].size();
vector row(R), col(C);
for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (p[i][j] == 'B') { row[i]++; col[j]++; }
int n = 0;
for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (p[i][j] == 'B' && row[i] == 1 && col[j] == 1) n++;
return n;
}
Explanation
A pixel is "lonely" when it is the only black "B" in its row AND the only one in its column. Instead of scanning a whole row and column for every cell, we precompute how many "B"s each row and each column has.
So we build two count arrays: row[i] = number of black pixels in row i, and col[j] = number in column j. This is a quick pass over the grid.
Then we count any cell (i, j) that is "B" and where row[i] == 1 and col[j] == 1. Those two conditions together mean it has no black neighbours in its row or column, so it is lonely.
This works because the row count and column count already summarize the whole line for us — we never have to re-scan.
Example: the diagonal picture [["W","W","B"],["W","B","W"],["B","W","W"]] has exactly one "B" in each row and each column, so all 3 are lonely and the answer is 3.