1252. Cells with Odd Values in a Matrix
Description
Given n
and m
which are the dimensions of a matrix initialized by zeros and given an array indices
where indices[i] = [ri, ci]
. For each pair of [ri, ci]
you have to increment all cells in row ri
and column ci
by 1.
Return the number of cells with odd values in the matrix after applying the increment to all indices
.
Example 1:
![](https://assets.leetcode.com/uploads/2019/10/30/e1.png)
Input: n = 2, m = 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 will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.
Example 2:
![](https://assets.leetcode.com/uploads/2019/10/30/e2.png)
Input: n = 2, m = 2, indices = [[1,1],[0,0]] Output: 0 Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.
Constraints:
1 <= n <= 50
1 <= m <= 50
1 <= indices.length <= 100
0 <= indices[i][0] < n
0 <= indices[i][1] < m
My Solution
Source Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @param {number} n
* @param {number} m
* @param {number[][]} indices
* @return {number}
*/
let oddCells = function(n, m, indices) {
let arr = [];
let numOdd = 0;
//set up array
for (let x = 0; x < n; x++) {
arr.push(new Array(m));
arr[x].fill(0);
}
for (let l = 0; l < indices.length; l++) {
//increment everything in the requested row
for (let i = 0; i < m; i++) {
let index = arr[indices[l][0]][i]++;
console.log(++index);
if ((index + 1) % 2 === 0) {
numOdd--;
} else {
numOdd++;
}
}
//increment everything in the requested column
for (let j = 0; j < n; j++) {
let index = arr[j][indices[l][1]]++;
if ((index + 1) % 2 === 0) {
numOdd--;
} else {
numOdd++;
}
}
}
console.log(arr);
return numOdd;
};
Analysis
There is nothing particularly special about my solution. First we set up the array of 0s. Then we iterate over the indices array and increase each specified row/column. As we do this, we check if the current element is odd and increase the counter if it is.
The running time for setting up the array is probably O(n*m) unless JavaScript's built in function for Array.fill() runs in constant time. The running time for actually solving the problem will be O(l*m + l*n) where l is length of the indices array.