CodeArchon

easyBinary SearchAmazonAppleBloomberg

Shelf Lookup

An archivist walks the shelf of SKU numbers (sorted) and jumps halfway each step to find a specific tag — or confirm it's not there.

Given a sorted `nums` array and `target`, return the index of target or −1 if absent. O(log n).

Choose approach

-1
0
lo
0
1
3
2
5
3
9
4
12
5
hi
1/3
Narrationstep 1 of 3

Binary search for 9 on sorted array. Keep [lo..hi]; probe the midpoint.

1def shelf_lookup(nums: list[int], target: int) -> int:
2 lo, hi = 0, len(nums) - 1
3 while lo <= hi:
4 mid = (lo + hi) // 2
5 if nums[mid] == target:
6 return mid
7 if nums[mid] < target:
8 lo = mid + 1
9 else:
10 hi = mid - 1
11 return -1
Variables
lo=0
hi=5
target=9

How to think about it

  1. Precondition: sorted array.
  2. Each probe halves the search space.
  3. Use `(lo + hi) >>> 1` (unsigned shift in Java) or `lo + (hi − lo)/2` to avoid overflow.
  4. Return −1 when lo exceeds hi.

Edge cases to catch in interview

  • Empty array → immediate −1.
  • Target at ends — handled.
  • Duplicates — returns some matching index (not necessarily first).

Examples

Example 14
{"nums":[-1,0,3,5,9,12],"target":9,"values":[-1,0,3,5,9,12]}
Example 2-1
{"nums":[-1,0,3,5,9,12],"target":2,"values":[-1,0,3,5,9,12]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed