Given a N x N binary matrix (elements in matrix can be either 1 or 0) where each row and column of the matrix is sorted in ascending order, count number of 0s present in it.
Expected time complexity is O(N).
Input: [0, 0, 0, 0, 1] [0, 0, 0, 1, 1] [0, 1, 1, 1, 1] [1, 1, 1, 1, 1] [1, 1, 1, 1, 1] Output: 8 Input: [0, 0] [0, 0] Output: 4 Input: [1, 1, 1, 1] [1, 1, 1, 1] [1, 1, 1, 1] [1, 1, 1, 1] Output: 0
The idea is very simple. We start from the bottom-left corner of the matrix and repeat below steps until we find the top or right edge of the matrix.
1. Decrement row index until we find a 0.
2. Add number of 0s in current column i.e. current row index + 1 to the result and move right to next column (Increment col index by 1).
The above logic will work since the matrix is row-wise and column-wise sorted. The logic will also work for any matrix containing non-negative integers.
Below is the implementation of above idea :
Time complexity of above solution is O(n) since the solution follows single path from bottom-left corner to top or right edge of the matrix.
Auxiliary space used by the program is O(1).
Do share with us if you find more interesting methods of solving this problem.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
- Search in a row wise and column wise sorted matrix
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
- Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
- Count number of islands where every island is row-wise and column-wise separated
- Print all elements in sorted order from row and column wise sorted matrix
- heapq in Python to print all elements in sorted order from row and column wise sorted matrix
- Row-wise vs column-wise traversal of matrix
- Sort the matrix row-wise and column-wise
- Check if the given matrix is increasing row and column wise
- Removing row or column wise duplicates from matrix of characters
- Find median in row wise sorted matrix
- Find a common element in all rows of a given row-wise sorted matrix
- Shift matrix elements row-wise by k
- Row-wise common elements in two diagonals of a square matrix