Problem - https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/
Approach -
Solution -
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
oddcount = 0
if ((n < 1 and n > 50) or (m < 1 and m > 50)):
return 0
matrix = [[0 for i in range(m)] for j in range(n)]
for idx in indices:
row, col = idx[0], idx[1]
for j in range(m):
matrix[row][j] += 1
for i in range(n):
matrix[i][col] += 1
for i in range(n):
for j in range(m):
if matrix[i][j] % 2:
oddcount += 1
return oddcount
Given
n
and m
which are the dimensions of a matrix initialized by zeros and given an array indices
where indices[i] = [ri, ci]
. For each pair of [ri, ci]
you have to increment all cells in row ri
and column ci
by 1.
Return the number of cells with odd values in the matrix after applying the increment to all
indices
.
Example 1:
Input: n = 2, m = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.
Approach -
- Iterate over indices and fetch row and column indices.
- First loop keep row index constant and increment column index and updated each cell values until it reaches column max size.
- Repeat same step and keep column index constant and increment row index and update all cell values until it reaches row max size.
- Iterate over matrix and count each cell value if divisible by 2 and keep count of odd numbers.
Solution -
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
oddcount = 0
if ((n < 1 and n > 50) or (m < 1 and m > 50)):
return 0
matrix = [[0 for i in range(m)] for j in range(n)]
for idx in indices:
row, col = idx[0], idx[1]
for j in range(m):
matrix[row][j] += 1
for i in range(n):
matrix[i][col] += 1
for i in range(n):
for j in range(m):
if matrix[i][j] % 2:
oddcount += 1
return oddcount
Comments