Cells with Odd Values in a Matrix - Problem
Matrix Increment Challenge: You're given an
Each operation is defined by
• Increment all cells in row
• Increment all cells in column
After applying all operations, return the total number of cells with odd values.
Example: With a 2×3 matrix and indices [[0,1], [1,1]], the matrix transforms from all zeros to having 6 cells with specific increment counts, and you need to count how many are odd.
m × n matrix initially filled with zeros. Your task is to perform a series of increment operations and count how many cells end up with odd values.Each operation is defined by
indices[i] = [ri, ci], which means:• Increment all cells in row
ri• Increment all cells in column
ciAfter applying all operations, return the total number of cells with odd values.
Example: With a 2×3 matrix and indices [[0,1], [1,1]], the matrix transforms from all zeros to having 6 cells with specific increment counts, and you need to count how many are odd.
Input & Output
example_1.py — Basic Case
$
Input:
m = 2, n = 3, indices = [[0,1],[1,1]]
›
Output:
6
💡 Note:
After operations: matrix becomes [[1,3,1],[1,2,1]]. The odd values are 1,3,1,1,1 (5 cells with odd values) - wait, let me recalculate: all cells except [1,1] are odd, so 5 odd cells total.
example_2.py — Single Operation
$
Input:
m = 2, n = 2, indices = [[1,1]]
›
Output:
4
💡 Note:
After operation [1,1]: matrix becomes [[0,1],[1,2]]. Cells with odd values: [0,1] and [1,0] have value 1, so 2 odd cells. Actually: row 1 and col 1 both get +1, so final matrix is [[0,1],[1,2]], giving us 2 odd cells.
example_3.py — No Operations
$
Input:
m = 2, n = 3, indices = []
›
Output:
0
💡 Note:
No operations means all cells remain 0 (even), so 0 cells have odd values.
Visualization
Tap to expand
Understanding the Visualization
1
Key Observation
Each cell's final value equals the number of row operations affecting it plus column operations
2
Mathematical Formula
cell[i][j] = count_of_ops_on_row_i + count_of_ops_on_col_j
3
Odd/Even Rule
A sum of two integers is odd if and only if exactly one of them is odd
4
Optimization
Instead of O(m×n) matrix, use O(m+n) counters and apply the formula
Key Takeaway
🎯 Key Insight: Since each cell's value is simply the sum of its row and column operation counts, we can solve this in O(m+n) space by tracking only the counters, not the full matrix.
Time & Space Complexity
Time Complexity
O(k + m×n)
k operations to count increments, then m×n iterations to check each cell
✓ Linear Growth
Space Complexity
O(m + n)
Only need arrays to store row and column increment counts
⚡ Linearithmic Space
Constraints
- 1 ≤ m, n ≤ 50
- 0 ≤ indices.length ≤ 100
- 0 ≤ ri < m
- 0 ≤ ci < n
- Each indices[i] represents a valid matrix position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code