Skip to main content

Posts

Showing posts from January, 2020

Cells with Odd Values in a Matrix

Problem -  https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ 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 s