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 One INPUT Binary Matrix (Row-sorted) col 0 col 1 row 0 0 0 row 1 1 1 Start: Top-Right Corner Input Details matrix = [[0,0],[1,1]] rows = 2, cols = 2 Access via BinaryMatrix API Max 1000 get() calls allowed ALGORITHM STEPS 1 Initialize Position row=0, col=cols-1 (top-right) 2 Check Current Cell Call get(row, col) 3 Move Based on Value If 1: move left (col--) If 0: move down (row++) 4 Repeat Until Done Stop when out of bounds Execution Trace (0,1): get=0 --> move down (1,1): get=1 --> move left (1,0): get=1 --> move left col=-1: OUT OF BOUNDS, ans=0 FINAL RESULT Leftmost Column Found col 0 0 1 col 1 0 1 Output 0 Verification [OK] Column 0 has a 1 at row 1 [OK] No column left of 0 exists [OK] Only 3 API calls made Key Insight: Starting from top-right corner leverages the row-sorted property. When we see a 1, we move left to find an earlier 1. When we see a 0, we move down since all cells to the left are also 0. This gives O(m+n) time complexity, using at most (rows + cols) API calls - well under the 1000 call limit. TutorialsPoint - Leftmost Column with at Least a One | Top-Right Corner Approach
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