#2482
Medium Algorithms Difference between ones and zeros in row and column
Array Matrix Simulation
84.4% acceptance
Feb 25, 2026
1242
86
You are given a 0-indexed m x n binary matrix grid.
diff[i][j] = onesRow_i + onesCol_j - zerosRow_i - zerosCol_j
Return the difference matrix diff.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn ones_minus_zeros(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let m = grid.len();
let n = grid[0].len();
let ones_row: Vec<i32> = grid.iter().map(|r| r.iter().sum()).collect();
let ones_col: Vec<i32> = (0..n).map(|j| grid.iter().map(|r| r[j]).sum()).collect();
(0..m).map(|i| {
(0..n).map(|j| {
2 * ones_row[i] - n as i32 + 2 * ones_col[j] - m as i32
}).collect()
}).collect()
}
}