Warehouse Bin Grid

Easybinary searchAlso known as Search a 2D Matrix

A parts warehouse stores coded bins on a wall of shelves. Codes grow left to right along a shelf, and each shelf starts above the last code of the shelf above it. Retired codes leave gaps.

Before climbing a ladder, a picker wants to know whether an ordered code exists anywhere on the wall.

Your task

Write hasBin(grid, code). grid[r][c] is the code on shelf r, position c. Every shelf has the same number of bins. Reading the shelves top to bottom, each left to right, gives one strictly increasing sequence.

Return true if code is in the grid, otherwise false. An empty grid (no shelves) returns false. Aim for O(log(rows × cols)).

hasBin(grid: int[][], code: int) → bool

Examples

Example 1
Input
grid = [[103, 108, 115, 121], [130, 134, 142, 150], [162, 170, 181, 199]]
code = 142
Output
true
Why

Laid end to end, the 12 codes form one sorted line. 142 is at position 6 of that line, which is shelf 1, slot 2.

Example 2
Input
grid = [[103, 108, 115, 121], [130, 134, 142, 150], [162, 170, 181, 199]]
code = 125
Output
false
Why

125 would sit between 121 (end of shelf 0) and 130 (start of shelf 1). Neither is 125, and nothing else can be, so the bin does not exist.

Constraints

  • 0 ≤ rows ≤ 200, and 1 ≤ cols ≤ 200 when rows > 0
  • 1 ≤ grid[r][c], code ≤ 1,000,000
  • Read row by row, the codes are strictly increasing.
Start with brute force

Checking every bin takes O(rows × cols) time, which is 40,000 bins for a 200 × 200 wall.

Binary searching each shelf is O(rows × log cols), but ignores that the shelves are sorted against each other. One binary search over the whole wall needs about 16 looks.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code