Binary Search

Easy

Topics
ArrayBinary Search

Given a sorted (ascending) array nums of distinct integers and a target, return its index, or -1 if not present. Must run in O(log n).

Example 1

-1001325394125
The values are sorted ascending, and the answer is the index of 9 rather than the value itself. It sits at index 4.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [-1,0,3,5,9,12], target = 9
Output: 4

Example 2

-1001325394125
It does not appear, and a missing target answers -1.
Input:  nums = [-1,0,3,5,9,12], target = 2
Output: -1

Constraints

  • 1 <= nums.length <= 10^4
  • nums is sorted ascending with distinct values.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A sorted array lets one comparison eliminate half the remaining candidates: compare the target to the middle and recurse into the half that could contain it.

Approach

  1. Keep an inclusive window [lo, hi].
  2. Compute mid; if it equals the target, return it.
  3. If the middle value is smaller, search the right half; otherwise the left half.
  4. An empty window means the target is absent → return -1.

Walkthrough

nums = [-1,0,3,5,9,12], target = 9
lo=0 hi=5 mid=2 (3) < 9 -> lo=3
lo=3 hi=5 mid=4 (9) == 9 -> return 4

Complexity

  • Time — O(log n): the search range halves each iteration.
  • Space — O(1): iterative with two indices.

Common Pitfalls

  • In languages with fixed-width ints, use lo + (hi - lo) // 2 to avoid overflow.
  • Use lo <= hi (inclusive) to not miss the last element.

Full Solution — all languages

class Solution:
    def search(self, nums, target):
        lo, hi = 0, len(nums) - 1
        while lo <= hi:
            mid = lo + (hi - lo) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
Asked at Cognizant
SensAI
Beta
Tap the mic to stop voice mode