Skip to content
Problem 704 · LeetCode 704(opens in a new tab)

Binary Search

EasyArrays

You get a list of whole numbers, nums, sorted from smallest to largest with no number appearing twice, and a number target.

Return the position (index) of target in nums, or −1 if it is not there. Your search has to run in O(log n) time, so reading every number is not allowed.

Example 1

Input:  nums = [-7, -2, 4, 6, 11, 15, 20], target = 11
Output: 4
Why:    11 sits at index 4
2 more examples and the constraints

Example 2

Input:  nums = [-7, -2, 4, 6, 11, 15, 20], target = 5
Output: -1
Why:    5 would fall between 4 and 6, but it is not in the list

Example 3

Input:  nums = [8], target = 8
Output: 0
Why:    the only number is the target

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • Every number, and the target, is strictly between −10,000 and 10,000
  • nums is sorted in increasing order and has no repeats

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Linear scanO(n)
  2. Binary searchO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 numbersVerdict
Linear scanO(n)
Correct, but breaks the O(log n) rule
Binary searchO(log n)
Best; about 14 checks

n = how many numbers are in the list.

Edge cases to test

  • One number. [8] with target 8 gives 0; with any other target, −1. This is where lo < hi goes wrong.
  • Target at either end. The first and last index must both be reachable.
  • Target outside the range. Smaller than the first number or larger than the last: return −1.
  • Target in a gap. 20 in [-30, -10, 0, 10, 30, 50] falls between two numbers, so the range shrinks to empty.

Common mistakes

  • Looping while lo < hi and never checking the last remaining number.
  • Setting lo = mid or hi = mid instead of mid ± 1, which can loop forever on two numbers.
  • Writing (lo + hi) / 2 in a language with fixed-size integers on huge arrays; lo + (hi - lo) / 2 cannot overflow.

How to talk through it

  1. 1Clarify. Is the list sorted in increasing order? Can numbers repeat? What should I return if the target is missing?
  2. 2Name the slow way. A scan is O(n) and ignores the sorting, so it misses the O(log n) requirement.
  3. 3State the invariant. If the target exists, it is always inside lo..hi. Each comparison keeps that true and halves the range.
  4. 4Code it carefully. Say why the loop is lo <= hi and why the pointers move to mid ± 1.
  5. 5Test out loud. Run a one-number list, the target at each end, and a missing target.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?