LeetCode 2482: Difference Between Ones and Zeros in Row and Column

ArrayMatrixSimulation

Problem Description

Explanation:

  • Calculate the number of ones and zeros in each row and each column.
  • For each cell in the matrix, compute the difference using the formula given in the problem description.
  • Return the resulting difference matrix.

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Space Complexity: O(m + n) for storing the counts of ones and zeros in rows and columns.

:

Solutions

class Solution {
    public int[][] differenceMatrix(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        int[] onesRow = new int[m];
        int[] onesCol = new int[n];
        int[] zerosRow = new int[m];
        int[] zerosCol = new int[n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                onesRow[i] += grid[i][j];
                onesCol[j] += grid[i][j];
                zerosRow[i] += 1 - grid[i][j];
                zerosCol[j] += 1 - grid[i][j];
            }
        }
        
        int[][] diff = new int[m][n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                diff[i][j] = onesRow[i] + onesCol[j] - zerosRow[i] - zerosCol[j];
            }
        }
        
        return diff;
    }
}

Loading editor...