Skip to main content
Back to problems
#533
Medium Algorithms

Lonely pixel ii

Array Hash Table Matrix
48.9% acceptance
Mar 31, 2026
93
788
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_black_pixel(picture: Vec<Vec<char>>, target: i32) -> i32 {
    use std::collections::HashMap;
    let m = picture.len();
    let n = picture[0].len();
    let mut col_count = vec![0i32; n];
    let mut row_map: HashMap<Vec<char>, i32> = HashMap::new();
    
    for i in 0..m {
      let row_b: i32 = picture[i].iter().filter(|&&c| c == 'B').count() as i32;
      for j in 0..n {
        if picture[i][j] == 'B' {
          col_count[j] += 1;
        }
      }
      if row_b == target {
        *row_map.entry(picture[i].clone()).or_insert(0) += 1;
      }
    }
    
    let mut count = 0;
    for (row, freq) in &row_map {
      if *freq != target { continue; }
      for j in 0..n {
        if row[j] == 'B' && col_count[j] == target {
          count += target;
        }
      }
    }
    count
  }
}