class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
rows = [0] * m
cols = [0] * n
for r, c in indices:
rows[r] += 1
cols[c] += 1
count = 0
for i in range(m):
for j in range(n):
if (rows[i] + cols[j]) % 2 == 1:
count += 1
return count
class Solution {
public:
int oddCells(int m, int n, vector<vector<int>>& indices) {
vector<int> rows(m, 0), cols(n, 0);
for (const auto& idx : indices) {
rows[idx[0]]++;
cols[idx[1]]++;
}
int count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if ((rows[i] + cols[j]) % 2 == 1)
count++;
}
}
return count;
}
};
class Solution {
public int oddCells(int m, int n, int[][] indices) {
int[] rows = new int[m];
int[] cols = new int[n];
for (int[] idx : indices) {
rows[idx[0]]++;
cols[idx[1]]++;
}
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((rows[i] + cols[j]) % 2 == 1)
count++;
}
}
return count;
}
}
var oddCells = function(m, n, indices) {
let rows = new Array(m).fill(0);
let cols = new Array(n).fill(0);
for (let [r, c] of indices) {
rows[r]++;
cols[c]++;
}
let count = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if ((rows[i] + cols[j]) % 2 === 1)
count++;
}
}
return count;
};
m x n
matrix initialized with all 0s. You are also given a list of indices
, where each element is a pair [ri, ci]
representing a row index and a column index. For each pair [ri, ci]
, every cell in row ri
and column ci
is incremented by 1. After performing all operations, your task is to return the number of cells in the matrix that have an odd value.
indices
can have repeated rows or columns.indices
and incrementing all elements in the corresponding row and column. However, this approach can be inefficient, especially for large matrices. Instead, let's consider what actually determines the final value of each cell:
(i, j)
is incremented every time its row i
or its column j
is targeted.(i, j)
after all operations is row_increments[i] + col_increments[j]
.rows
of size m
and cols
of size n
.[ri, ci]
in indices
, increment rows[ri]
and cols[ci]
by 1.(i, j)
, its final value is rows[i] + cols[j]
.
This approach is efficient because it avoids modifying the entire matrix and only needs two passes: one to process indices
and one to count odd cells.
m = 2
, n = 3
, indices = [[0,1],[1,1]]
rows = [0, 0]
and cols = [0, 0, 0]
.[0,1]
: rows = [1, 0]
, cols = [0, 1, 0]
[1,1]
: rows = [1, 1]
, cols = [0, 2, 0]
rows[i] + cols[j]
:
6
.