Upper Bound

Pattern: Binary search on sorted arrays

medium

The first index whose value is strictly bigger than x, or n if there is none. It is the lower bound with > instead of ≥, and the two together count copies of a value.

The problem

You are given a sorted array, which may have repeated values, and a number x. Return the upper bound of x: the smallest index i with nums[i] > x. If no value is bigger than x, return the array's length. For example, [1, 2, 2, 3] with x = 2 gives 3, and [3, 5, 8, 15, 19] with x = 9 gives 3.

The function name upperBound matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • How does this differ from Lower Bound in one character?
  • Where does the upper bound of x land when x appears several times?
  • What is upper bound minus lower bound?

Hints

    Brute force, and why it fails

    Scan for the first value above x: O(n). Binary search finds it in O(log n).

    The key insight

    The test nums[i] > x is false for a prefix and then true. Its first yes is the upper bound, and the yes/no template finds it unchanged.

    Dry run

    10lo
    21 
    22 
    33 

    nums = [1, 2, 2, 3] and x = 2. The test is "value above 2", which reads no, no, no, yes.

    Step 1 of 3

    The plan

    lo = 0, hi = n
    while lo < hi:
        mid = lo + (hi - lo) / 2
        if nums[mid] > x: hi = mid
        else: lo = mid + 1
    return lo
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    Each step halves the range.

    Edge cases

    • x equal to the last value, as in [3, 5, 8, 15, 19] with x = 19: the answer is n.
    • x below every value: 0.
    • All values equal to x: n.
    I've built my logic, show the code

    Java

    class Solution {
        public int upperBound(int[] nums, int x) {
            int lo = 0, hi = nums.length;           // the answer is in [lo, hi]
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] > x) hi = mid;        // mid is bigger: the first bigger one is here or to the left
                else lo = mid + 1;                  // mid is at most x
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        int upperBound(vector<int>& nums, int x) {
            int lo = 0, hi = static_cast<int>(nums.size());   // the answer is in [lo, hi]
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] > x) hi = mid;        // mid is bigger: the first bigger one is here or to the left
                else lo = mid + 1;                  // mid is at most x
            }
            return lo;
        }
    };

    Python

    class Solution:
        def upperBound(self, nums: list[int], x: int) -> int:
            lo, hi = 0, len(nums)                   # the answer is in [lo, hi]
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] > x:
                    hi = mid                        # mid is bigger: the first bigger one is here or to the left
                else:
                    lo = mid + 1                    # mid is at most x
            return lo

    Common mistakes

    • Using ≥, which gives the lower bound instead.
    • Expecting the index of the last copy of x. The upper bound is one past it.
    • Starting hi at n - 1.

    Similar problems