
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Column Index of Left-Most 1 in Binary Matrix using Python
Suppose we have a 2D binary matrix. Here each row is sorted in ascending order with 0s coming before 1s, we have to find the leftmost column index with the value of 1. If there's no such result, return -1.
So, if the input is like
0 | 0 | 0 | 1 |
0 | 0 | 1 | 1 |
0 | 0 | 1 | 1 |
0 | 0 | 1 | 0 |
then the output will be 2, as the second column has left most 1 in entire matrix.
To solve this, we will follow these steps:
-
if matrix is empty, then
return -1
N := row count of matrix
M := column count of matrix
i := 0, j := M - 1
leftmost := -1
-
while i < N and j >= 0, do
-
if matrix[i, j] is same as 0, then
i := i + 1
-
otherwise,
leftmost := j
j := j - 1
-
return leftmost
Example
class Solution: def solve(self, matrix): if not matrix or not matrix[0]: return -1 N = len(matrix) M = len(matrix[0]) i = 0 j = M - 1 leftmost = -1 while i < N and j >= 0: if matrix[i][j] == 0: i += 1 else: leftmost = j j -= 1 return leftmost ob = Solution() matrix = [ [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0] ] print(ob.solve(matrix))
Input
[ [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0] ]
Output
2
Advertisements