Workspace

Problem workspace

3 day streakD

Lower Bound & Search Insert Position

EasyBinary SearchSearch & boundaries

The challenge

Return the first index i with nums[i] ≥ target. Return n if every value is smaller. This is the sorted insertion position.

Ascending order; duplicates allowed. Empty input returns 0. The result can be one past the last index.

Example

[1, 2, 2, 2, 5, 8], target = 2 → 1; target = 9 → 6.

Use the walkthrough below to inspect the input and each state change.

See Lower bound, step by step

Inspect the comparison, the invariant, and the next boundary.

Inclusive candidate indicestarget = 2
L = 0 · mid = — · R = 5102122235485
Current comparisonResolved positionNumbers below = indices
Left
0
Middle
—
Right
5
Step 01 / 6

Find the first value ≥ target

Reset the inclusive candidate interval. The returned boundary is allowed to equal the array length.

left = 0; right = 5

Recorded result so far

Not resolved
View exact input

Input: [1,2,2,2,5,8] · target = 2

Put it into code

Search for the false-to-true boundary of nums[i] ≥ target. Equality must continue toward the left.

Indices are zero-based. C++ uses C++17 or later.

def lower_bound(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = left + (right - left) // 2
        if nums[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return left  # len(nums) if no value qualifies.

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap