File: cells-with-odd-values-in-a-matrix/solution.py

Date: 2026-06-06

Time: 15:33

Purpose

This file is the solution and test suite for LeetCode 1252: Cells with Odd Values in a Matrix. It owns a single responsibility: given an m x n matrix initialized to zeros and a list of [row, col] index pairs, count how many cells end up with odd values after incrementing every cell in the specified row and every cell in the specified column for each pair.

Key Components

Solution.oddCells(m, n, indices) -> int

The core algorithm. Rather than simulating the full matrix (O(m*n) per operation), it exploits the fact that each cell's final value is rowcount[r] + colcount[c] — the number of times its row was hit plus the number of times its column was hit. A cell is odd when exactly one of those two counts is odd (odd + even = odd, even + odd = odd).

This leads to the closed-form return on line 23:


odd_rows * (n - odd_cols) + (m - odd_rows) * odd_cols

TestOddCells

Nine test cases covering: LeetCode examples, single-cell matrices, single-row/column, all rows and columns hit, repeated indices, and a stress test (100 identical operations on a 50x50 matrix).

Patterns

Dependencies

Imports: unittest (stdlib), typing.List (type annotation only — not needed at runtime in modern Python).

Imported by: The testsolution.py files listed in the prompt don't actually import *this* file — the "Imported By" section appears to be a repo-wide cross-reference artifact. The real consumer is cells-with-odd-values-in-a-matrix/testsolution.py.

Flow

1. Initialize rowcount[0..m-1] and colcount[0..n-1] to zero.

2. For each [r, c] in indices, increment rowcount[r] and colcount[c].

3. Count how many row counts are odd (oddrows) and how many column counts are odd (oddcols).

4. Return the number of (row, col) pairs where exactly one of rowcount[row] and colcount[col] is odd.

Invariants

Error Handling

None. The function trusts its inputs match LeetCode constraints (valid indices within bounds, m/n >= 1). No bounds checking or exception handling — appropriate for a competitive programming context.

Complexity

Topics to Explore

Beliefs