
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Write Python program to find duplicate rows in a binary matrix
- Program to find out if a BST is present in a given binary tree in Python
- Program to find most frequent subtree sum of a binary tree in Python
- Program to find out if a linked list is present in a given binary tree in Python
- Program to find number of special positions in a binary matrix using Python
- Program to find out the index of the most frequent element in a concealed array in Python
- C++ Program to Find Deepest Left Leaf in a Binary Tree
- Program to find out the index in an array where the largest element is situated in Python
- Program to find valid matrix given row and column sums in Python
- Program to check if a matrix is Binary matrix or not in C++
- Program to find index whose left and right elements sums are equal in Python
- Find maximum path length in a binary matrix in Python
- Program to find index, where we can insert element to keep list sorted in Python
- Program to find minimum cost to reach final index with at most k steps in python
- Nearest 1 in a binary matrix in C++

Advertisements