Cells with Odd Values in a Matrix
Given n (rows) and m (columns), create a matrix of zeros. Then apply operations from an indices array where each [ri, ci] increments all cells in row ri and all cells in column ci. Return the count of odd-valued cells after all operations.
Instead of simulating the full matrix, track row counts and column counts. Each operation increments a row and a column. The final value at cell (i,j) is rowCounts[i] + colCounts[j]. A cell is odd if this sum is odd.
Track the number of rows with odd count and columns with odd count. The number of odd cells is: oddRows * colCount + oddCols * rowCount - 2 * oddRows * oddCols. Because cells at the intersection of odd rows and odd columns are counted twice and should be even.
Time is O(len(indices)) with O(n + m) space, much better than O(n * m * len(indices)).
The matrix cell parity problem demonstrates how tracking row and column counts avoids simulating the full matrix. The count of odd cells formula uses inclusion-exclusion: oddRows * m + oddCols * n - 2 * oddRows * oddCols accounts for cells counted twice.
The parity tracking approach demonstrates how DP can avoid O(n*m) simulation by using aggregated state variables for rows and columns.Example Input & Output
All even.
Cell (0,1) is odd.
6 odd cells.
Cells (0,1) and (1,0) are odd.
No ops.
Algorithm Flow

Solution Approach
Track row and col counts. Count odd rows and odd cols. Use formula to compute odd cells.
Time O(n+m+k), Space O(n+m).
Best Answers
class Solution {
public int solution(int n, int m, int[][] indices) {
int[] r=new int[n]; int[] c=new int[m];
for (int[] idx : indices) { r[idx[0]]++; c[idx[1]]++; }
int or=0,oc=0;
for (int x:r) if (x%2==1) or++;
for (int x:c) if (x%2==1) oc++;
return or*m + oc*n - 2*or*oc;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
