Leftmost Column with at Least a One Problem
Description
LeetCode Problem 1428.
A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(row, col)returns the element of the matrix at index(row, col)(0-indexed).BinaryMatrix.dimensions()returns the dimensions of the matrix as a list of 2 elements[rows, cols], which means the matrix isrows x cols.
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, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.
Example 1:

Input: mat = [[0,0],[1,1]]
Output: 0
Example 2:

Input: mat = [[0,0],[0,1]]
Output: 1
Example 3:

Input: mat = [[0,0],[0,0]]
Output: -1
Constraints:
rows == mat.lengthcols == mat[i].length1 <= rows, cols <= 100mat[i][j]is either0or1.mat[i]is sorted in non-decreasing order.
Solution
Approach: Staircase Walk from the Top-Right Corner
Reading the whole matrix would take up to 104 calls, but only 1000 are allowed. The sorted rows let us throw away a whole row or column with each call.
Start at the top-right cell (0, cols - 1) and look at its value:
- It is
1: this column has a 1, so it is a candidate answer. Anything further right is worse, so move left to look for a smaller column. - It is
0: since the row is sorted, every cell to the left in this row is also 0. This row can not give anything better, so move down.
Stop when we leave the matrix. The last column where we saw a 1 is the answer, or -1 if we never saw one.
Each step moves left or down, so there are at most rows + cols calls, at most 200 here. (Binary searching each row also fits, at about rows · log(cols) ≈ 700 calls, but the walk is simpler and cheaper.)
Complexity: O(rows + cols) time and calls to get, O(1) extra space.
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
# class BinaryMatrix(object):
# def get(self, row: int, col: int) -> int:
# def dimensions(self) -> List[int]:
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
rows, cols = binaryMatrix.dimensions()
# Walk from the top-right corner: a 1 means the answer is this column or further left,
# a 0 means nothing to the left in this row is a 1, so go down.
row, col = 0, cols - 1
ans = -1
while row < rows and col >= 0:
if binaryMatrix.get(row, col) == 1:
ans = col
col -= 1
else:
row += 1
return ans