Leftmost column with a one in a row-sorted binary matrix
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's technical phone screen, last asked May 2026. It tests binary-search and matrices.
You have an m x n matrix of 0s and 1s in which every row is sorted: all of a row's 0s come before its 1s. Return the index of the leftmost column that contains a 1 in any row, or -1 if the matrix has no 1. You can read the matrix only through an API, and every read counts, so the goal is to read far fewer than m × n cells.
Interface
Unless you agree on a different interface with the interviewer, assume:
class BinaryMatrix:
def get(self, row: int, col: int) -> int: ...
def dimensions(self) -> tuple[int, int]: ... # (m, n)
-
leftmost_column_with_one(matrix: BinaryMatrix) -> int— a 0-based column index, or -1.
Example
[[0, 0, 0, 1],
[0, 1, 1, 1],
[0, 0, 1, 1]] -> 1 # row 1 has its first 1 in column 1
[[0, 0],
[0, 0]] -> -1
Constraints
-
1 <= m, n <= 100. - Each row is all 0s, all 1s, or 0s followed by 1s.
- Reading every cell is too slow. O(m log n) reads is an acceptable first step; aim for about
m + n.
Clarifying questions
- Is the index 0-based?
- Which costs matter: the number of
getcalls or the running time? - Can a row be all 0s or all 1s?
- Is
mmuch larger thann, or the reverse? That decides between the two approaches.
What a strong answer covers
- First approach: binary search each row for its first 1 and take the minimum, O(m log n) reads.
- Better: start at the top-right corner; on a 1 move left, on a 0 move down. At most
m + nreads, O(1) space. - Why the staircase walk never skips the answer.
- When binary search per row wins (few rows, very wide rows).
- Tests: no 1s, all 1s, a single row, a single column.
Follow-ups
- Return every row that has its first 1 in the answer column.
- Rows are sorted but the API can only read whole columns. What changes?
- Find the row with the most 1s using the same walk.
Where it's asked
- Uber · Technical phone screen · Last asked May 202660 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design
What it tests
binary-search · matrices
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
