Only increment parity matters. Toggle row and column parity for each operation, then count cells whose two parities differ.
Complexity
O(k + nm) time and O(n + m) space.
Count odd matrix cells after incrementing selected rows and columns.
Only increment parity matters. Toggle row and column parity for each operation, then count cells whose two parities differ.
O(k + nm) time and O(n + m) space.
package main
func oddCells(m int, n int, indices [][]int) int {
rows, columns := make([]bool, m), make([]bool, n)
for _, index := range indices {
rows[index[0]] = !rows[index[0]]
columns[index[1]] = !columns[index[1]]
}
odd := 0
for _, row := range rows {
for _, column := range columns {
if row != column {
odd++
}
}
}
return odd
}
class Solution:
def oddCells(self, m: int, n: int, indices: list[list[int]]) -> int:
rows, columns = [False] * m, [False] * n
for row, column in indices: rows[row] = not rows[row]; columns[column] = not columns[column]
return sum(row != column for row in rows for column in columns)
function oddCells(m: number, n: number, indices: number[][]): number {
const rows = new Array<boolean>(m).fill(false); const columns = new Array<boolean>(n).fill(false);
for (const [row, column] of indices) { rows[row] = !rows[row]; columns[column] = !columns[column]; }
let odd = 0; for (const row of rows) for (const column of columns) if (row !== column) odd += 1; return odd;
}