KatInterview

Leftmost Column Containing a One in Row-Sorted Grid

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashingmatrixtwo-pointersbinary-matrix

Last updated

Find the leftmost column holding a 1 in a binary grid whose rows are sorted, aiming for a linear-time walk instead of scanning every cell.

Leftmost Column Containing a One

You are given a grid of 0s and 1s with rows rows and cols columns. Within every row the values are sorted in non-decreasing order, so each row is a block of 0s followed by a block of 1s (either block may be empty).

Return the index (0-based) of the leftmost column that contains at least one 1. If the grid contains no 1 at all, return -1.

In the original setting each cell lookup is considered costly, so a good solution reads as few cells as possible. Aim for a solution that reads at most about rows + cols cells rather than inspecting all rows * cols of them.

Function

Implement leftmost_one_column(rows, cols, grid):

  • rows: the number of rows in the grid.
  • cols: the number of columns in the grid.
  • grid: a list of rows lists, each with cols integers (0 or 1), every row sorted in non-decreasing order.

Return a single integer: the smallest column index containing a 1, or -1 if there is none.

Constraints

  • 1 <= rows, cols <= 10^5
  • Every entry of grid is 0 or 1.
  • Each row of grid is sorted in non-decreasing order.
  • Treat each access grid[r][c] as an expensive read and try to keep the number of reads low.

Edge cases to handle

  • A grid made entirely of 0s returns -1.
  • A grid made entirely of 1s returns 0.
  • Grids with a single row or a single column.

Examples

Example 1

Input: leftmost_one_column(3, 4, [[0, 0, 1, 1], [0, 0, 0, 1], [0, 1, 1, 1]])

Output: 1

Example 2

Input: leftmost_one_column(2, 3, [[0, 0, 0], [0, 0, 0]])

Output: -1

Hints

Hint 1

Because each row is sorted, a 0 at some position means everything to its left in that row is also 0.

Hint 2

Start at the top-right cell and keep a column pointer that never moves right. What should you do on a 1, and what on a 0?

Hint 3

On a 1, remember the column and step left; on a 0, drop to the next row without changing the column. Each read either moves the pointer left or finishes a row, so at most rows + cols reads happen.