leftmost-column-with-at-least-a-one
Problem
Leftmost Column with at Least a One
Problem Description
(This problem is an interactive problem.)
A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).
BinaryMatrix.dimensions() returns a list of 2 elements [m, n], which means the matrix is m * n.
Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.
Solution
Solution #1 - Binary Search
BinaryMatrix row is sorted, and find left most 1, binary search in O(logN), record each row left most column index with 1, each row do binary search, and compare the left most column, keep track of min column number. after iterate through all rows, return min.
Complexity Analysis
Time Complexity: O(MlogN)
Space Complexity: O(1)
M - the number of rows in binaryMatrix
N - the number of columns in binaryMatrix
Code
Solutions #2 -- Linear Time
Start from up-right corner, (m, n)
init start position:
row = 0, col = n - 1, res = -1if current position value,
binaryMatrix.get(row, col) = 1, updateres = col, move left, row = row - 1if current position,
binaryMatrix.get(row, col) = 0, move down,col = col - 1continue until one dimension out of boundry. return res.
For example:

Complexity Analysis
Time Complexity: O(M+N)
Space Complexity: O(1)
M - the number of rows in binaryMatrix
N - the number of columns in binaryMatrix
Last updated
Was this helpful?