#1582
Easy Algorithms Special positions in a binary matrix
Array Matrix
68.8% acceptance
Feb 25, 2026
1514
76
Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn num_special(mat: Vec<Vec<i32>>) -> i32 {
let m = mat.len();
let n = mat[0].len();
let row_sum: Vec<i32> = mat.iter().map(|row| row.iter().sum()).collect();
let col_sum: Vec<i32> = (0..n).map(|c| (0..m).map(|r| mat[r][c]).sum()).collect();
let mut count = 0;
for r in 0..m {
for c in 0..n {
if mat[r][c] == 1 && row_sum[r] == 1 && col_sum[c] == 1 {
count += 1;
}
}
}
count
}
}