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 Between Ones and Zeros INPUT Binary Matrix grid (3x3) 0 1 1 1 0 1 0 0 1 Row 0 Row 1 Row 2 Row Statistics ones: [2, 2, 1] zeros: [1, 1, 2] Column Statistics ones: [1, 1, 3] zeros: [2, 2, 0] ALGORITHM 1 Count Row Ones onesRow = [2, 2, 1] 2 Count Col Ones onesCol = [1, 1, 3] 3 Compute Zeros zeros = n - ones 4 Apply Formula diff[i][j] = oR + oC - zR - zC Example: diff[0][2] onesRow[0] = 2 onesCol[2] = 3 zerosRow[0] = 1 zerosCol[2] = 0 2 + 3 - 1 - 0 = 4 FINAL RESULT Difference Matrix diff 0 0 4 0 0 4 -2 -2 2 Output Array [[0,0,4],[0,0,4],[-2,-2,2]] Legend Positive: more 1s Negative: more 0s Zero: balanced Key Insight: Precompute ones count for each row and column in O(m+n) time. Then for each cell, zeros = size - ones. Final formula: diff[i][j] = onesRow[i] + onesCol[j] - zerosRow[i] - zerosCol[j] Time: O(m*n) | Space: O(m+n) TutorialsPoint - Difference Between Ones and Zeros in Row and Column | Precompute Row/Column Stats
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