Problem Statement
You are given a binary matrix (only 0s and 1s) binaryMatrix
where:
- Each row is sorted in non-decreasing order (0s followed by 1s).
- You need to find the leftmost column index (0-based) that contains at least one 1.
- If no such column exists, return
-1
.
You can access the matrix only through an API:
int get(int row, int col) // returns the value at row, col List<Integer> dimensions() // returns [rows, cols]
Goal: Minimize the number of get()
calls.
Example
Input: binaryMatrix = [ [0,0,0,1], [0,0,1,1], [0,1,1,1] ] Output: 1 Explanation: Column 1 is the leftmost column containing a 1.
Key Observations
- Rows are sorted. So all 1s in a row appear to the right of 0s.
- You can start from the top-right corner:
- If you see
1
, move left (maybe there is a 1 further left). - If you see
0
, move down (this row has no 1s before this column).
- If you see
- This ensures O(rows + cols) time complexity.
Approach: Top-Right Pointer
- Get the matrix dimensions:
rows
andcols
. - Initialize:
row = 0
(top row)col = cols - 1
(rightmost column)
- Initialize
leftmostCol = -1
(default if no 1 found) - While
row < rows
andcol >= 0
:- If
binaryMatrix.get(row, col) == 1
:- Update
leftmostCol = col
- Move left:
col--
- Update
- Else:
- Move down:
row++
- Move down:
- If
- Return
leftmostCol
.
Java Code
/** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation * interface BinaryMatrix { * public int get(int row, int col) {} * public List<Integer> dimensions() {} * } */ import java.util.List; public class LeftmostColumnWithOne { public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { List<Integer> dims = binaryMatrix.dimensions(); int rows = dims.get(0); int cols = dims.get(1); int row = 0; int col = cols - 1; int leftmostCol = -1; while (row < rows && col >= 0) { if (binaryMatrix.get(row, col) == 1) { leftmostCol = col; // Update the leftmost 1 col--; // Move left } else { row++; // Move down } } return leftmostCol; } }
Dry Run Example
Input Matrix
[0, 0, 0, 1] [0, 0, 1, 1] [0, 1, 1, 1]
- Start at
row=0, col=3
→ value = 1 → updateleftmostCol=3
, move leftcol=2
row=0, col=2
→ value = 0 → move downrow=1
row=1, col=2
→ value = 1 → updateleftmostCol=2
, move leftcol=1
row=1, col=1
→ value = 0 → move downrow=2
row=2, col=1
→ value = 1 → updateleftmostCol=1
, move leftcol=0
row=2, col=0
→ value = 0 → move downrow=3
→ exit loop
Return: 1