Warehouse Bin Grid

Easybinary searchAlso known as Search a 2D Matrix

A parts warehouse stores bins on a wall of shelves. Each bin has a code. The codes grow from left to right along a shelf, and each shelf starts with a code larger than the last code on the shelf above it. Some codes were retired, so the numbers skip.

A picker gets an order for a code and wants to know, before climbing a ladder, whether that bin 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

Check every bin, shelf by shelf. That is O(rows × cols): 40,000 bins for a 200 × 200 wall.

A middle ground is to binary search each shelf separately, O(rows × log cols). Better, but it still 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