Skip to content
DSA Patterns
Menu
Language
Binary SearchLC #353 of 6← PreviousNext →

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

Search Insert Position

Problem (restated)

Given a sorted distinct array, return the index of target, or where it would be inserted to keep order.

Intuition

Classic lower_bound: first index with nums[i] ≥ target.

Approaches

Lower bound binary search

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

Idea. lo/hi half-open. When mid < target, lo=mid+1 else hi=mid. Answer is lo.

Walkthrough. [1,3,5,6], target=5 → 2; target=2 → 1; target=7 → 4.

Trade-offs. Linear scan is O(n); binary search is required pattern practice.

Solution
export function searchInsert(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;
}
export function searchInsert(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;
}

Template connection

Lower bound: the first index with nums[i] >= target. A smaller nums[mid] moves lo to mid + 1. Otherwise hi moves to mid. If every value is smaller, the answer is n.

Reflection

  • “Where it would be inserted” is the lower bound. When the loop ends, why is lo that index?
  • A target smaller than every element returns 0. Larger than every element returns n.
  • Why does lo + ((hi - lo) >> 1) avoid the overflow?
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 6
1/6

Insert position of 2 in a sorted distinct array: lower bound.

1
0
3
1
5
2
6
3

target = 2

Key:Active rangeMatchSettledEliminated