Cells with Odd Values in a Matrix - Problem

Given an m x n matrix initialized to all zeros, and a 2D array indices where each indices[i] = [ri, ci] represents a location to perform increment operations.

For each location indices[i], do both of the following:

  • Increment all cells in row ri
  • Increment all cells in column ci

Return the number of cells with odd values in the matrix after applying all increment operations.

Input & Output

Example 1 — Basic Case
$ Input: m = 2, n = 3, indices = [[0,1],[1,1]]
Output: 6
💡 Note: Matrix starts as zeros. After [0,1]: increment row 0 and column 1. After [1,1]: increment row 1 and column 1 again. Final matrix [[1,3,1],[1,3,1]] has 6 odd values.
Example 2 — Single Operation
$ Input: m = 2, n = 2, indices = [[1,1]]
Output: 2
💡 Note: After [1,1]: increment row 1 and column 1. Final matrix [[0,1],[1,2]] has 2 odd values at positions (0,1) and (1,0).
Example 3 — No Operations
$ Input: m = 2, n = 2, indices = []
Output: 0
💡 Note: No operations performed, matrix remains all zeros, so 0 odd values.

Constraints

  • 1 ≤ m, n ≤ 50
  • 1 ≤ indices.length ≤ 100
  • 0 ≤ ri < m
  • 0 ≤ ci < n

Visualization

Tap to expand
Cells with Odd Values in a Matrix INPUT m = 2, n = 3 Initial Matrix (all zeros): 0 0 0 0 0 0 r0 r1 c0 c1 c2 indices array: [0, 1] [1, 1] For each [ri, ci]: 1) Increment row ri 2) Increment col ci m=2, n=3 indices=[[0,1],[1,1]] ALGORITHM STEPS 1 Process [0,1] Inc row 0, Inc col 1 1 2 1 0 1 0 2 Process [1,1] Inc row 1, Inc col 1 1 3 1 1 2 1 3 Track row/col counts rows=[1,1], cols=[0,2,0] 4 Count odd cells odd row + even col OR even row + odd col Row inc Col inc Both FINAL RESULT Final Matrix: 1 3 1 1 2 1 = Odd value Odd Value Count: Row 0: 1, 3, 1 3 odd Row 1: 1, 2, 1 3 odd Total: 6 odd OUTPUT 6 OK - 6 cells have odd values Key Insight: A cell [i,j] has odd value if (row_count[i] + col_count[j]) is odd. This happens when exactly one of row_count[i] or col_count[j] is odd (XOR logic). Optimal: Count odd rows (r) and odd cols (c). Answer = r*(n-c) + c*(m-r). Time: O(indices + m + n) TutorialsPoint - Cells with Odd Values in a Matrix | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
125.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen