Lower Bound

Pattern: Binary search on sorted arrays

medium

The first index whose value is at least x, or n if there is none. This one search is the building block for insert positions, first occurrences and counts.

The problem

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

The function name lowerBound matches the takeUforward practice page. Use the link above for the exact statement and limits. C++ has this built in as std::lower_bound, and Python as bisect.bisect_left, but write it yourself.

Think first

  • Write "no" or "yes" under each value for the test "value ≥ x". What shape do you get?
  • Which index is the answer in that picture?
  • When nums[mid] is a yes, can you throw mid itself away?

Hints

    Brute force, and why it fails

    Scan from the left for the first value at least x: O(n). On a sorted array the yes/no boundary can be found by halving, in O(log n).

    The key insight

    Because the array is sorted, the test nums[i] ≥ x is false for a prefix and true for the rest. Binary search finds where it turns true, and when there are repeats it lands on the first copy.

    Dry run

    30lo
    51 
    82 
    153 
    194 

    nums = [3, 5, 8, 15, 19] and x = 9. The answer lies in lo..hi, and hi = 5 stands for "none".

    Step 1 of 4

    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 hi - lo.

    Edge cases

    • x above every value: the answer is n.
    • x below every value: the answer is 0.
    • Many copies of x: the answer is the first copy, as in [4, 4, 4] with x = 4 giving 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int lowerBound(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 qualifies: the first one is here or to the left
                else lo = mid + 1;                  // mid is too small
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        int lowerBound(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 qualifies: the first one is here or to the left
                else lo = mid + 1;                  // mid is too small
            }
            return lo;
        }
    };

    Python

    class Solution:
        def lowerBound(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 qualifies: the first one is here or to the left
                else:
                    lo = mid + 1                    # mid is too small
            return lo

    Common mistakes

    • Returning as soon as nums[mid] == x, which may not be the first copy.
    • Starting hi at n - 1, so the answer n is never possible.
    • Using > in the test, which turns it into the upper bound.

    Similar problems