#1252

Cells with Odd Values in a Matrix

Easy
ArrayMathSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m + n + k)
Space
O(1)
O(m + n)
💡

Intuition

Time O(m + n + k)Space O(m + n)

Instead of simulating the entire matrix, we can keep track of how many times each row and column is incremented. This allows us to calculate the final odd counts without constructing the full matrix.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two arrays to count increments for rows and columns.
  2. 2Step 2: For each index in the indices array, increment the corresponding row and column counts.
  3. 3Step 3: Calculate the number of odd cells based on the counts from the two arrays.
solution.py14 lines
1# Full working Python code
2
3def oddCells(m, n, indices):
4    row_count = [0] * m
5    col_count = [0] * n
6    for r, c in indices:
7        row_count[r] += 1
8        col_count[c] += 1
9    odd_count = 0
10    for r in row_count:
11        for c in col_count:
12            if (r + c) % 2 != 0:
13                odd_count += 1
14    return odd_count

Complexity note: The time complexity is O(m + n + k) where k is the number of indices since we only iterate through the row and column counts and the indices. The space complexity is O(m + n) due to the additional arrays used to store the counts.

  • 1Tracking increments separately for rows and columns allows for efficient calculation of odd cells.
  • 2The final odd count can be determined by the parity of row and column increments.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.