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
Difficulty
and has an acceptance rate of about 80% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Simulation
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 944: Delete Columns to Make Sorted
- problem 1030: Matrix Cells in Distance Order
- problem 1200: Minimum Absolute Difference
- problem 1290: Convert Binary Number in a Linked List to Integer
- problem 419: Battleships in a Board
- problem 816: Ambiguous Coordinates
- problem 866: Prime Palindrome
- problem 926: Flip String to Monotone Increasing
- problem 962: Maximum Width Ramp
- problem 979: Distribute Coins in Binary Tree
Extra
- 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