← DiffPush

Find x in sorted array

Baseline Binary Search · 1D Arrays O(log n) · O(1)

The Archive Index Lookup

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.

Constraints

Examples

Example 1

Input: {"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.

Example 2

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.

Solve this in your browser →

Also on LeetCode ↗