1051. Leftmost Lit Column

Medium3.5 points estimatedMatrixBinary SearchInteractive3 hints

An indicator board has rows of bulbs, and in every row the bulbs have been sorted so that all the unlit bulbs (0) come first and all the lit bulbs (1) come after them. You cannot see the board directly. Instead, grid.get(row, col) returns the bulb state, and grid.dimensions() returns [rows, cols].

Return the smallest column index that contains at least one lit bulb, or -1 if every bulb is unlit. Reading the whole board is not allowed: you may make at most 250 calls in total (including dimensions), so aim for O(rows + cols) calls.

Example 1

Input:
grid = [[0,0,1],[0,1,1],[0,0,0]]
Output:
1
Explanation:

Column 1 is the leftmost column that contains a lit bulb (in the middle row).

Example 2

Input:
grid = [[0,0],[0,0]]
Output:
-1
Explanation:

No bulb is lit anywhere, so the answer is -1.

Constraints

1 ≤ rows, cols ≤ 100
Each row is non-decreasing (0s then 1s)
At most 250 calls to grid.get and grid.dimensions

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Calls
You may call BinaryMatrix.get(row, col), BinaryMatrix.dimensions() at most 250 times per case. It is provided; you do not write it.

Expected complexity

Time
O(rows + cols) calls
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…