# 2482. Difference Between Ones and Zeros in Row and Column

• Time: $O(mn)$
• Space: $O(mn)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { public: vector> onesMinusZeros(vector>& grid) { const int m = grid.size(); const int n = grid[0].size(); vector> ans(m, vector(n)); vector onesRow; vector onesCol; for (const vector& row : grid) onesRow.push_back(count(begin(row), end(row), 1)); for (int j = 0; j < n; ++j) { int ones = 0; for (int i = 0; i < m; ++i) ones += grid[i][j]; onesCol.push_back(ones); } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) ans[i][j] = onesRow[i] + onesCol[j] - (n - onesRow[i]) - (m - onesCol[j]); return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public int[][] onesMinusZeros(int[][] grid) { final int m = grid.length; final int n = grid[0].length; int[][] ans = new int[m][n]; int[] onesRow = new int[m]; int[] onesCol = new int[n]; for (int i = 0; i < m; ++i) onesRow[i] = (int) Arrays.stream(grid[i]).filter(a -> a == 1).count(); for (int j = 0; j < n; ++j) { int ones = 0; for (int i = 0; i < m; ++i) ones += grid[i][j]; onesCol[j] = ones; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) ans[i][j] = onesRow[i] + onesCol[j] - (n - onesRow[i]) - (m - onesCol[j]); return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution: def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]: m = len(grid) n = len(grid[0]) ans = [[0] * n for _ in range(m)] onesRow = [row.count(1) for row in grid] onesCol = [col.count(1) for col in zip(*grid)] for i in range(m): for j in range(n): ans[i][j] = onesRow[i] + onesCol[j] - \ (n - onesRow[i]) - (m - onesCol[j]) return ans