progress

~/problems / Binary search / Binary search

Binary Search

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

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. Don't use list.index, in, or the bisect module: keep a range [lo, hi] that might still hold the target and halve it each step.

⭐ Bonus: a speed test with many searches over a million elements earns a star at O(log n) per search.

C++ / Java: you write searchAll(nums, targets), returning search(nums, target) for each target in targets. 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