Cells with Odd Values in a Matrix — LeetCode 1252 Python Solution

EasyArrayMathSimulation
Problem
#1252
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(k \times (m + n) + m \times n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview