Binary Search
Problem
You are given an array of integers nums sorted in non-decreasing order and an integer target. Return the index at which target appears in nums. If it does not appear, return -1. A linear scan is not an acceptable answer; the solution should do logarithmically many comparisons.
numsmay be empty and holds at most 50,000 elements.- Values and
targetare integers in the range -100,000 to 100,000. - If
targetoccurs more than once, any matching index is acceptable.
Examples
nums = [2, 4, 7, 10, 15, 21, 30], target = 15→4, becausenums[4] == 15.nums = [2, 4, 7, 10, 15, 21, 30], target = 8→-1; 8 falls between 7 and 10 but is not present.nums = [3], target = 3→0. A one-element array still needs the loop to terminate correctly.
Hints
- The array is sorted. Comparing
targetto one element tells you which side it could be on. - Keep two indices that bracket the region where the answer could still live, and shrink that region every step.
- Classic binary search with an inclusive
[lo, hi]window; stop when the window is empty.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.