Leftmost Column with at Least a One - Problem

You are given a row-sorted binary matrix where all elements are either 0 or 1, and each row is sorted in non-decreasing order.

Your task is to find the leftmost column that contains at least one 1. Return the 0-indexed column number, or -1 if no such column exists.

Important constraints:

  • You cannot access the matrix directly
  • You can only use the BinaryMatrix interface with methods:
    • get(row, col) - returns the element at position (row, col)
    • dimensions() - returns [rows, cols] as a list
  • Your solution must make at most 1000 calls to BinaryMatrix.get()

Input & Output

Example 1 — Basic Case
$ Input: binaryMatrix = [[0,0],[1,1]]
Output: 0
💡 Note: The leftmost column with a 1 is column 0. Row 1 has a 1 at position (1,0).
Example 2 — No Ones
$ Input: binaryMatrix = [[0,0],[0,0]]
Output: -1
💡 Note: There are no 1s in the matrix, so return -1.
Example 3 — Multiple Rows
$ Input: binaryMatrix = [[0,0,1],[0,1,1],[0,0,1]]
Output: 1
💡 Note: The leftmost column with a 1 is column 1. Row 1 has the first 1 at position (1,1).

Constraints

  • rows == mat.length
  • cols == mat[i].length
  • 1 ≤ rows, cols ≤ 100
  • mat[i][j] is either 0 or 1
  • mat[i] is sorted in non-decreasing order

Visualization

Tap to expand
Leftmost Column with at Least a OneInput Matrix001111Col 0Col 1Col 2Find leftmost column containing at least one 1Result0Column IndexColumn 0 has a 1 in row 1 → Answer: 0
Understanding the Visualization
1
Input
Row-sorted binary matrix via BinaryMatrix interface
2
Process
Find leftmost column with any 1 using minimal API calls
3
Output
Return column index or -1 if no 1s exist
Key Takeaway
🎯 Key Insight: Use the sorted property to eliminate entire rows/columns with strategic traversal from top-right corner
Asked in
Facebook 8 Google 5 Amazon 3
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen