- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# Program to find column index where left most 1 is present in a binary matrix in 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

- Related Questions & Answers
- Program to find out if a BST is present in a given binary tree in Python
- Program to find out if a linked list is present in a given binary tree in Python
- Write Python program to find duplicate rows in a binary matrix
- Program to find most frequent subtree sum of a binary tree in Python
- Nearest 1 in a binary matrix in C++
- C++ Program to Find Deepest Left Leaf in a Binary Tree
- Find if there is a rectangle in binary matrix with corners as 1 in C++
- Program to find number of special positions in a binary matrix using Python
- Program to find out the index in an array where the largest element is situated in Python
- Program to find index whose left and right elements sums are equal in Python
- Program to check if a matrix is Binary matrix or not in C++
- Program to find out the index of the most frequent element in a concealed array in Python
- Find maximum path length in a binary matrix in Python
- How to find a value is present in binary tree or not in JavaScript ?
- C++ code to find index where this is a hash collision

Advertisements