#2482
Difference Between Ones and Zeros in Row and Column
MediumArrayMatrixSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n) |
| Space | O(1) | O(m + n) |
💡
Intuition
Time O(m * n)Space O(m + n)
In the optimal solution, we first calculate the number of ones in each row and column in a single pass. This allows us to reuse these counts when calculating the difference matrix, significantly reducing redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Create two arrays to store the count of ones in each row and each column.
- 2Step 2: Traverse the grid to populate these arrays.
- 3Step 3: Use the counts from the arrays to compute the diff matrix in a single pass.
solution.py18 lines
1# Full working Python code
2
3def differenceMatrix(grid):
4 m, n = len(grid), len(grid[0])
5 onesRow = [0] * m
6 onesCol = [0] * n
7 diff = [[0] * n for _ in range(m)]
8 for i in range(m):
9 for j in range(n):
10 if grid[i][j] == 1:
11 onesRow[i] += 1
12 onesCol[j] += 1
13 for i in range(m):
14 for j in range(n):
15 zerosRow = n - onesRow[i]
16 zerosCol = m - onesCol[j]
17 diff[i][j] = onesRow[i] + onesCol[j] - zerosRow - zerosCol
18 return diffℹ
Complexity note: The time complexity is O(m * n) because we make a single pass through the grid to count ones and then another pass to compute the diff matrix. The space complexity is O(m + n) due to the two arrays used to store counts.
- 1Reusing computed values can significantly reduce time complexity.
- 2Understanding how to manipulate counts can simplify complex calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.