Workspace

Problem workspace

3 day streakD

Upper Bound

EasyBinary SearchSearch & boundaries

The challenge

Return the first index i with nums[i] > target, or n if no value qualifies.

Ascending order; duplicates allowed. Empty input returns 0.

Example

[1, 2, 2, 2, 5, 8], target = 2 → 4.

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

See Upper 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

Use a strict predicate. Equal values belong on the discarded left side, so the search moves beyond the entire duplicate run.

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

def upper_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