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
0lo
0
13
25
39
412
5hi
1/3
Narrationstep 1 of 3
Binary search for 9 on sorted array. Keep [lo..hi]; probe the midpoint.
Variables
lo=0
hi=5
target=9
How to think about it
- Precondition: sorted array.
- Each probe halves the search space.
- Use `(lo + hi) >>> 1` (unsigned shift in Java) or `lo + (hi − lo)/2` to avoid overflow.
- 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 1
4{"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