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
๐ The Challenge: You cannot access the matrix directly! Instead, you must use a special
โข
โข
โ ๏ธ Constraint: You can make at most 1000 calls to
Example: In a 4ร4 matrix where column 1 is the leftmost column containing a 1, you should return
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
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
-
rows == binaryMatrix.dimensions()[0] -
cols == binaryMatrix.dimensions()[1] -
1 โค rows, cols โค 100 -
binaryMatrix[i][j]is either0or1 - 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code