Skip to content
DSA Patterns
Menu
Language
Binary SearchLC #7046 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Binary Search

Problem (restated)

Given a sorted array of distinct integers and a target, return the index of target or -1.

Intuition

Classic lower-bound binary search on a sorted array.

Approaches

Lower-bound binary search

Unverified
Time O(log n)Space O(1)

Idea. lo=0, hi=n exclusive; while lo<hi mid=…; if nums[mid]<target lo=mid+1 else hi=mid. Check nums[lo].

Walkthrough. nums=[-1,0,3,5,9,12], target=9 → index 4.

Trade-offs. Iterative form avoids recursion depth concerns.

Solution
export function search(nums: number[], target: number): number {
  let lo = 0, hi = nums.length;
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (nums[mid]! < target) lo = mid + 1;
    else hi = mid;
  }
  return lo < nums.length && nums[lo] === target ? lo : -1;
}
export function search(nums: number[], target: number): number {
  let lo = 0, hi = nums.length;
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (nums[mid]! < target) lo = mid + 1;
    else hi = mid;
  }
  return lo < nums.length && nums[lo] === target ? lo : -1;
}

Template connection

mid is lo + (hi - lo) // 2, so the sum of the ends cannot overflow. An equal value returns mid. A smaller nums[mid] sets lo to mid + 1. A larger one sets hi to mid - 1. An empty range means the target is absent.

Reflection

  • Classic binary search. Mixing a closed [lo, hi] loop with a half-open [lo, hi) template produces which off-by-one?
  • A missing target returns −1. How does returning on equality differ from the bound search in LC 34?
  • What do you return for an empty array?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1/8

Half-open search space [lo, hi). Target = 9.

lo
-1
0
0
1
3
2
mid
5
3
9
4
hi
12
5
Statetarget=9lo=0mid=3hi=5

a[mid] = 5 < 9

Key:CurrentActive rangeMatchSettledEliminated