Binary Search
Find the target in a sorted array. Return any matching zero-based index, or -1.
Find the target in a sorted array. Return any matching zero-based index, or -1.
Input and constraints
- Values must be in nondecreasing order.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): left = 0 right = (len(values) - 1) while (left <= right): mid = (left + ((right - left) // 2)) if (values[mid] == target): return mid if (values[mid] < target): left = (mid + 1) else: right = (mid - 1) return -1Visualizer
Step 1 of 6Inspect the current state
Inspect midpoint 4 within the remaining bounds.
Variable watch
Step explanation
Inspect midpoint 4 within the remaining bounds.
Worked explanation
A librarian opens the middle of a sorted catalogue and closes an entire half after each comparison.
Guided solution
Check the midpoint of the inclusive range. Sorted order tells you which half cannot contain the target.
O(log n) time · O(1) auxiliary space
Examples
Worked example · {"values":[2,5,8,12,16,23,38,56,72],"target":23} ⇒ 5
Edge case 1 · {"values":[],"target":3} ⇒ -1
Edge case 2 · {"values":[2],"target":3} ⇒ -1
Edge case 3 · {"values":[4],"target":4} ⇒ 0
Progressive hints
Hint 1
A librarian opens the middle of a sorted catalogue and closes an entire half after each comparison.Hint 2
Check the midpoint of the inclusive range. Sorted order tells you which half cannot contain the target.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Updating a boundary to mid instead of moving past it can repeat the same interval forever.
Interview follow-up
How would the boundaries change if you needed the first match?