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

0001
0011
0011
0010

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

 Live Demo

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

Updated on: 10-Nov-2020

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements