CodingNodes / Binary Search / Binary Search System design Space play · ←→ step · R restart

Problem

You get an array nums of distinct integers sorted from smallest to largest, and a number target.

Return the index where target sits in nums, or -1 if it is not there. Your solution has to run in O(log n) time.

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • −10⁴ < nums[i], target < 10⁴
  • All values in nums are distinct and sorted in increasing order

Examples: pick one to animate

Solutions

TimeO(log n) SpaceO(1)

Time: Every probe throws away at least half of the remaining indices, so there are at most about log2(n) probes.

Space: Only lo, hi and mid are stored. The array is never copied.

Keep a range [lo, hi] that could still hold the target. Look at the middle value. If it matches, done. If it is too small, move lo past it; if it is too big, move hi before it.