Leftmost Column with at Least a One - Problem
Interactive Matrix Problem: You're given a row-sorted binary matrix where each row contains only 0s and 1s arranged in non-decreasing order (all 0s come before all 1s in each row). Your task is to find the leftmost column that contains at least one 1.

๐Ÿ”’ The Challenge: You cannot access the matrix directly! Instead, you must use a special BinaryMatrix interface with two methods:
โ€ข get(row, col) - returns the element at position (row, col)
โ€ข dimensions() - returns [rows, cols] as the matrix dimensions

โš ๏ธ Constraint: You can make at most 1000 calls to get() method. If no column contains a 1, return -1.

Example: In a 4ร—4 matrix where column 1 is the leftmost column containing a 1, you should return 1.

Input & Output

example_1.py โ€” Standard Case
$ Input: matrix = [[0,0,0,1],[0,0,1,1],[0,1,1,1],[0,0,0,1]]
โ€บ Output: 1
๐Ÿ’ก Note: The leftmost column with at least one 1 is column index 1. Row 2 has a 1 at column 1, which is the earliest position where any 1 appears in the matrix.
example_2.py โ€” No Ones Matrix
$ Input: matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
โ€บ Output: -1
๐Ÿ’ก Note: There are no 1s in the entire matrix, so we return -1 as specified when no column contains a 1.
example_3.py โ€” First Column Has One
$ Input: matrix = [[1,1,1,1],[0,0,0,1],[0,0,1,1],[0,1,1,1]]
โ€บ Output: 0
๐Ÿ’ก Note: The very first column (index 0) contains a 1 in the first row, making it the leftmost column with at least one 1.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(rows ร— cols)

In worst case, we check every cell in the matrix

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • rows == binaryMatrix.dimensions()[0]
  • cols == binaryMatrix.dimensions()[1]
  • 1 โ‰ค rows, cols โ‰ค 100
  • binaryMatrix[i][j] is either 0 or 1
  • Each row of the matrix is sorted in non-decreasing order
  • You cannot access the matrix directly - only through the BinaryMatrix interface
  • You can make at most 1000 calls to BinaryMatrix.get
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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