Skip to content

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<vector<int>> onesMinusZeros(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<vector<int>> ans(m, vector<int>(n));
    vector<int> onesRow;
    vector<int> onesCol;

    for (const vector<int>& row : grid)
      onesRow.push_back(ranges::count(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