Leftmost Column with atleast one 1 in a row | JavaScript implementation to find the Leftmost Column with atleast a 1 in a sorted binary matrix ; Function to search for the leftmost column of the matrix with atleast a 1 in sorted binary matrix ; Loop to iterate over all the rows of the matrix ; Binary Search to find the leftmost occurence of the 1 ; Condition if the column contains the 1 at this position of matrix ; If there is a better solution then update the answer ; Condition if the solution doesn 't exist in the matrix ; Driver Code
var N = 3 ; function search ( mat , n , m ) { var i , a = 1000000000 ; for ( i = 0 ; i < n ; i ++ ) { var low = 0 ; var high = m - 1 ; var mid ; var ans = 1000000000 ; while ( low <= high ) { mid = parseInt ( ( low + high ) / 2 ) ; if ( mat [ i ] [ mid ] == 1 ) { if ( mid == 0 ) { ans = 0 ; break ; } else if ( mat [ i ] [ mid - 1 ] == 0 ) { ans = mid ; break ; } } if ( mat [ i ] [ mid ] == 1 ) high = mid - 1 ; else low = mid + 1 ; } if ( ans < a ) a = ans ; } if ( a == 1000000000 ) return - 1 ; return a + 1 ; } var mat = [ [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] , [ 0 , 1 , 1 ] ] ; document . write ( search ( mat , 3 , 3 ) ) ;