First value at least target

Lesson 4.3 · Easy · Find a boundary · 6 min · by Vinay C

We'll cover the following

In a sorted array, find the first index whose value is at least the target. This is also where the target would be inserted.

Watch it run

Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.

20 items · 6 steps
lo110
141
162
283
294
405
476
497
538
mid549
5610
6011
6312
7213
7314
7715
8416
8917
9218
hi9619

54 ≥ 17. This could be the answer. Remember it and look left for an earlier one.

candidate 9

1 / 6

The idea

Complexity

TimeSpaceWhy
O(log n)O(1)The range halves every step.

In Python

def lower_bound(nums, target):
    lo, hi, ans = 0, len(nums) - 1, len(nums)
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] >= target:
            ans = mid; hi = mid - 1
        else:
            lo = mid + 1
    return ans

Summary: say it in the interview

  • When the middle value works, it might be the answer, but an earlier one might too. Remember it and keep searching left. This "find the first that works" shape is the most useful form of binary search.
  • Time O(log n), space O(1). The range halves every step.