LeetCode 1428. Leftmost Column with at Least a One Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1428. Leftmost Column with at Least a One

Description

A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.

Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.

You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:

  • BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).
  • BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.

Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.

 

Example 1:

Input: mat = [[0,0],[1,1]]
Output: 0

Example 2:

Input: mat = [[0,0],[0,1]]
Output: 1

Example 3:

Input: mat = [[0,0],[0,0]]
Output: -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.

Solutions

Solution 1: Binary Search

First, we call BinaryMatrix.dimensions() to get the number of rows m and columns n of the matrix. Then for each row, we use binary search to find the column number j where the leftmost 1 is located. The smallest j value that satisfies all rows is the answer. If there is no such column, return -1.

The time complexity is O(m × log n), where m and n are the number of rows and columns of the matrix, respectively. We need to traverse each row, and use binary search within each row, which has a time complexity of O(log n). The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#
# """ # This is BinaryMatrix's API interface. # You should not implement it, or speculate about its implementation # """ # class BinaryMatrix(object): # def get(self, row: int, col: int) -> int: # def dimensions(self) -> list[]: class Solution: def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int: m, n = binaryMatrix.dimensions() ans = n for i in range(m): j = bisect_left(range(n), 1, key=lambda k: binaryMatrix.get(i, k)) ans = min(ans, j) return -1 if ans >= n else ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !