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 ith row be onesRowi.
  • Let the number of ones in the jth column be onesColj.
  • Let the number of zeros in the ith row be zerosRowi.
  • Let the number of zeros in the jth column be zerosColj.
  • 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
Difference Matrix: Transform Binary Grid to Difference ValuesInput Grid0111Row 0: 1 one, 1 zeroRow 1: 2 ones, 0 zerosCol 0: 1 one, 1 zeroCol 1: 2 ones, 0 zerosOutput Matrix0224Formula: onesRow + onesCol - zerosRow - zerosColExample: diff[0][0] = 1+1-1-1 = 0Example: diff[1][1] = 2+2-0-0 = 4Each cell combines its row and column statistics
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
Asked in
Microsoft 15 Amazon 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen