Cells with Odd Values in a Matrix — LeetCode 1252 Python Solution
- Problem
- #1252
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.
Example
- Input
- m = 2, n = 3, indices = [[0,1],[1,1]]
- Output
- 6
- Explanation
- Initial matrix = [[0,0,0],[0,0,0]].
Python solution
class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
g = [[0] * n for _ in range(m)]
for r, c in indices:
for i in range(m):
g[i][c] += 1
for j in range(n):
g[r][j] += 1
return sum(v % 2 for row in g for v in row)Complexity
| Measure | Complexity |
|---|---|
| Time | O(k \times (m + n) + m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1252. Cells with Odd Values in a Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1252. Cells with Odd Values in a Matrix?
- LeetCode 1252. Cells with Odd Values in a Matrix is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1252. Cells with Odd Values in a Matrix?
- The Python solution on this page runs in O(k \times (m + n) + m \times n).
- What is the space complexity of LeetCode 1252. Cells with Odd Values in a Matrix?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 1252. Cells with Odd Values in a Matrix cover?
- LeetCode 1252. Cells with Odd Values in a Matrix is tagged Array, Math and Simulation on LeetCode.