Magicsheet logo

Cells with Odd Values in a Matrix

Easy
12.5%
Updated 8/1/2025

Asked by 2 Companies

Cells with Odd Values in a Matrix

What is this problem about?

The "Cells with Odd Values in a Matrix interview question" involves updating a grid based on a series of operations. You start with an mimesnm imes n matrix filled with zeros. You are given an array of indices, where each index [r,c][r, c] tells you to increment all elements in row rr and all elements in column cc by 1. The goal is to find the total number of cells in the matrix that contain an odd value after all operations are complete.

Why is this asked in interviews?

Google and Microsoft ask the "Cells with Odd Values in a Matrix coding problem" to evaluate a candidate's ability to optimize a simulation. While a brute-force approach (updating the whole matrix for each operation) is possible, interviewers want to see if you can recognize that you only need to track the number of times each row and column was incremented. It tests "Array interview pattern" and "Simulation" optimization skills.

Algorithmic pattern used

This problem can be solved using Simulation or Counting Parity.

  1. Row and Column Tracking: Create two arrays, row_counts and col_counts, to store how many times each row and column were modified.
  2. Final Parity Check: A cell (r,c)(r, c) will be odd if row_counts[r] + col_counts[c] is an odd number.
  3. Mathematical Optimization: You can further optimize by counting how many rows are incremented an odd number of times (RoddR_{odd}) and how many columns are odd (CoddC_{odd}). The total odd cells can be calculated using parity logic: (Roddimesn)+(Coddimesm)2imes(RoddimesCodd)(R_{odd} imes n) + (C_{odd} imes m) - 2 imes (R_{odd} imes C_{odd}).

Example explanation

m=2,n=3m=2, n=3, indices = [[0,1]]

  1. Row 0 is incremented: [1, 1, 1], [0, 0, 0]
  2. Column 1 is incremented: [1, 2, 1], [0, 1, 0] Final matrix: [[1, 2, 1], [0, 1, 0]] Odd values are at (0,0), (0,2), (1,1). Total: 4. (Wait, let's re-verify: (0,0)=1, (0,1)=2, (0,2)=1, (1,0)=0, (1,1)=1, (1,2)=0. Yes, 4 odd values).

Common mistakes candidates make

  • Brute Force Inefficiency: Updating the entire row and column for every entry in indices, leading to O(Limes(M+N))O(L imes (M+N)) where LL is the length of indices. The optimized approach is O(L+M+N)O(L + M + N).
  • Space Complexity: Creating a full 2D matrix when only row and column frequency arrays are needed.
  • Parity Logic Errors: Miscalculating the formula for odd cells if attempting the O(1)O(1) space (mathematical) optimization.

Interview preparation tip

Always look for ways to avoid "actually doing" the simulation if the result only depends on the final state. Tracking cumulative changes in separate arrays is a classic "Simulation interview pattern" trick.

Similar Questions