~/problems / Binary search / Binary search

Binary Search

easy ~15 min

Write search(nums: list[int], target: int) -> int.

nums is sorted in strictly increasing order (no duplicates). Return the index of target in nums, or -1 if it isn't there.

Example: nums = [-4, 0, 3, 8, 15], target = 8 gives 3; target = 5 gives -1.

Constraints: 0 <= len(nums) <= 10^6, many queries against the same list.

Your search must be O(log n): keep a range [lo, hi] that still might hold the target and halve it each step. Don't use list.index, in, or the bisect module; a linear scan fails the performance test, which runs thousands of searches over a million elements.

C++ / Java: you write searchAll(nums, targets), which returns search(nums, t) for every t in targets, in order, so the tests can run many searches on one big list. Write search as a helper and call it in a loop.

Topic: Binary search. lo/hi invariants, lower vs upper bound, rotated arrays, bisect.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc