Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find column index where left most 1 is present in a binary matrix in Python?
Suppose we have a 2D binary matrix where each row is sorted in ascending order with 0s coming before 1s. We need to find the leftmost column index that contains the value 1. If no such column exists, return -1.
So, if the input is like ?
| 0 | 0 | 0 | 1 |
| 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | 0 |
Then the output will be 2, as column index 2 has the leftmost 1 in the entire matrix.
Algorithm
To solve this efficiently, we will follow these steps ?
- If matrix is empty, return -1
- N := row count of matrix
- M := column count of matrix
- Start from top-right corner: i = 0, j = M - 1
- leftmost := -1
- While i < N and j >= 0:
- If matrix[i][j] == 0, move down (i += 1)
- Otherwise, update leftmost = j and move left (j -= 1)
- Return leftmost
Implementation
class Solution:
def solve(self, matrix):
if not matrix or not matrix[0]:
return -1
N = len(matrix)
M = len(matrix[0])
i = 0
j = M - 1
leftmost = -1
while i < N and j >= 0:
if matrix[i][j] == 0:
i += 1
else:
leftmost = j
j -= 1
return leftmost
# Test the solution
ob = Solution()
matrix = [
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 0]
]
result = ob.solve(matrix)
print(f"Leftmost column with 1: {result}")
Leftmost column with 1: 2
How It Works
The algorithm uses a clever approach by starting from the top-right corner of the matrix:
- If current element is 0, we move down because all elements to the left in this row are also 0
- If current element is 1, we found a potential answer and move left to find an even earlier column with 1
- This ensures we find the leftmost column containing 1 in O(M + N) time complexity
Alternative Approach Using Built-in Functions
def find_leftmost_one(matrix):
if not matrix or not matrix[0]:
return -1
leftmost = -1
for row in matrix:
try:
# Find first occurrence of 1 in this row
first_one = row.index(1)
if leftmost == -1 or first_one < leftmost:
leftmost = first_one
except ValueError:
# No 1 found in this row
continue
return leftmost
# Test the alternative approach
matrix = [
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 0]
]
result = find_leftmost_one(matrix)
print(f"Leftmost column with 1: {result}")
Leftmost column with 1: 2
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Top-right traversal | O(M + N) | O(1) | Optimal solution |
| Built-in index() | O(M × N) | O(1) | Simple implementation |
Conclusion
The top-right traversal approach is optimal with O(M + N) time complexity. It leverages the sorted property of rows to efficiently find the leftmost column containing 1 without checking every element.
Advertisements
