Cells with Odd Values in a Matrix Problem
Description
LeetCode Problem 1252.
There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [r_i, c_i] represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i], do both of the following:
- Increment all the cells on row
r_i. - Increment all the cells on column
c_i.
Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.
Example 1:

Input: m = 2, n = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.
Example 2:

Input: m = 2, n = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.
Constraints:
1 <= m, n <= 501 <= indices.length <= 1000 <= r_i < m0 <= c_i < n
Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?
Solution
Approach: Count Odd Rows and Columns
We do not need to build the matrix. A cell (i, j) ends up with the number of times row i was incremented plus the number of times column j was incremented. Only the parity of each count matters, so we keep one flag per row and one per column and flip it for every [r, c] in indices.
A sum of two numbers is odd when exactly one of them is odd. So if oddRows rows and oddCols columns were incremented an odd number of times, the odd cells are:
- the cells in an odd row and an even column:
oddRows × (n - oddCols); - the cells in an even row and an odd column:
(m - oddRows) × oddCols.
A cell in an odd row and an odd column is even, which is why it is not counted. In Example 1, row 0 and row 1 are each hit once (both odd) and column 1 is hit twice (even), so the answer is 2 × 3 + 0 = 6.
Complexity: O(m + n + L) time and O(m + n) space, where L is the length of indices. This is the follow-up's bound.
class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
# Only the parity of how often each row and each column was incremented matters.
row_odd = [False] * m
col_odd = [False] * n
for r, c in indices:
row_odd[r] = not row_odd[r]
col_odd[c] = not col_odd[c]
odd_rows = sum(row_odd)
odd_cols = sum(col_odd)
# A cell is odd when exactly one of its row and its column is odd.
return odd_rows * (n - odd_cols) + (m - odd_rows) * odd_cols