Baseline Binary Search · 1D Arrays O(log n) · O(1)
A robotic archivist stores shelf labels in one strictly increasing index and must fetch the exact shelf holding a requested call number. Because the index is sorted, the robot can discard half of the remaining shelves after a single probe instead of walking the aisle. Report the shelf position when the call number exists, or signal that it does not.
Input: An array nums of n integers sorted in ascending order with distinct values, and an integer target.
Output: The 0-indexed position of target in nums, or -1 when target is absent.
1 <= n <= 5000-10^4 < nums[i], target < 10^4All values in nums are uniquenums is sorted in ascending orderInput: {"nums":[-1,0,3,5,9,12],"target":9}
Output: 4
Probing the middle shelves repeatedly narrows the search to index 4, where 9 lives.
Input: {"nums":[-1,0,3,5,9,12],"target":2}
Output: -1
The search space collapses to an empty range without ever matching 2, so the lookup reports -1.