Difference Between Ones and Zeros in Row and Column - Problem
You are given a 0-indexed m x n binary matrix grid.
A 0-indexed m x n difference matrix diff is created with the following procedure:
- Let the number of ones in the
ithrow beonesRowi. - Let the number of ones in the
jthcolumn beonesColj. - Let the number of zeros in the
ithrow bezerosRowi. - Let the number of zeros in the
jthcolumn bezerosColj. diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj
Return the difference matrix diff.
Input & Output
Example 1 — Basic 2x2 Matrix
$
Input:
grid = [[0,1,1],[1,0,1],[0,0,1]]
›
Output:
[[0,0,4],[0,0,4],[-2,-2,2]]
💡 Note:
For cell (0,0): Row 0 has 2 ones and 1 zero, Column 0 has 1 one and 2 zeros. Formula: 2+1-1-2 = 0
Example 2 — Simple 2x2
$
Input:
grid = [[1,1,1],[1,1,1]]
›
Output:
[[5,5,5],[5,5,5]]
💡 Note:
All ones matrix: Each row has 3 ones, each column has 2 ones. Formula: 3+2-0-0 = 5 for every cell
Example 3 — All Zeros
$
Input:
grid = [[0,0],[0,0]]
›
Output:
[[-4,-4],[-4,-4]]
💡 Note:
All zeros: Each row has 0 ones and 2 zeros, each column has 0 ones and 2 zeros. Formula: 0+0-2-2 = -4
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 105
- 1 ≤ m * n ≤ 105
- grid[i][j] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Binary matrix with 0s and 1s
2
Count Statistics
Count ones/zeros per row and column
3
Apply Formula
Calculate onesRow + onesCol - zerosRow - zerosCol
Key Takeaway
🎯 Key Insight: Precompute row/column statistics once, then apply formula to each cell
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code