Problem 1252

Abstract / Summary

After applying increment operations to matrix cells, count how many cells have odd values.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1252.py

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

        result = 0
        for y in range(m):
            for x in range(n):
                result += (rows[y] + cols[x]) & 1
        return result
13 lines | 381 bytes | submitted December 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of counting cells with odd values after a series of increment operations on an m by n matrix. Each operation increments every element in a specified row and a specified column. Instead of materializing the full matrix, the algorithm tracks the number of times each row and each column is incremented. The final count of odd cells is derived from the parity of the combined row and column increments for every position.

Key Steps

The algorithm begins by allocating two one-dimensional counters, one for rows and one for columns. Both counters are initialized to zero, establishing a clean state before any increments are applied.

rows = [0] * m
cols = [0] * n

Next, the method iterates over the list of index pairs. For each pair, the corresponding row counter and column counter are increased by one. This step captures the cumulative effect of all operations without touching the matrix itself.

for r, c in indices:
    rows[r] += 1
    cols[c] += 1

After all increments have been recorded, the algorithm proceeds to evaluate every cell. For each cell at coordinates (y, x), the sum of the row counter and the column counter determines the final value of that cell. The expression (rows[y] + cols[x]) & 1 extracts the least-significant bit, yielding 1 when the sum is odd and 0 when it is even. The result accumulator is incremented by this bit, effectively counting odd cells.

result = 0
for y in range(m):
    for x in range(n):
        result += (rows[y] + cols[x]) & 1
return result

Edge Cases

When the matrix dimensions are zero, the initial row and column lists become empty. The subsequent loops over ranges of length zero execute no iterations, and the function correctly returns 0 as there are no cells to evaluate.

If the list of indices is empty, the row and column counters remain at zero. The parity check then evaluates to 0 for every cell, leading to a result of 0, which matches the expectation that no increments produce only even (zero) values.

The algorithm also gracefully handles duplicate index pairs. Each occurrence increments the same row and column counters again, and the parity calculation naturally reflects the total number of increments, ensuring that cells toggled an even number of times are counted as even.

When m or n equals 1, the nested loops collapse to a single dimension, but the same parity logic applies, correctly counting odd cells in a single row or column scenario.

Performance Optimizations

The most significant optimization is the avoidance of an explicit m by n matrix. By storing only the counts for rows and columns, memory usage is reduced to m + n integers, regardless of the total number of cells.

The use of the bitwise AND operator with 1 to test oddness is a low-level operation that executes faster than a modulo operation. This choice speeds up the inner loop that processes every cell.

The algorithm’s two-phase structure-first aggregating increments, then scanning the matrix-ensures that each index pair is processed exactly once, and each cell is examined exactly once, providing a tight execution path without redundant work.

Overall, the design leverages simple integer arithmetic and direct array indexing, both of which are highly cache-friendly and benefit from modern CPU pipelines, resulting in an efficient solution for the given problem.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid of squares on the floor, like a sheet of graph paper. Every square starts with a number zero inside it. The code begins by creating a list to keep track of how many times each row is tapped and another list for how many times each column is tapped.

When the code looks at the instructions provided in the list called indices, it finds a row number and a column number. It then goes to that row and adds one to a counter, and it goes to that column and adds one to a different counter. This happens for every single instruction given.

After all those taps are finished, the code looks at every single square on the grid one by one. To figure out if a square has an odd number inside, it adds the total taps from that square's row to the total taps from that square's column. The special math symbol with the number one checks if the final total is odd or even. If the total is odd, that square gets counted.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.14

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
30 links | 20 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality