Floor and Ceil in Sorted Array

Pattern: Binary search on sorted arrays

medium

The floor is the largest value at most x and the ceil is the smallest value at least x. Two binary searches, each remembering the best candidate it has seen, find them both.

The problem

You are given a sorted array, which may repeat values, and a number x. Return [floor, ceil]. The floor is the largest value that is at most x, and the ceil is the smallest value that is at least x. Use -1 for one that does not exist. For example, [3, 4, 4, 7, 8, 10] gives [4, 7] for x = 5, [8, 8] for x = 8, and [-1, 3] for x = 2.

The function name getFloorAndCeil matches the takeUforward practice page. Use the link above for the exact statement and limits. Note that the answer holds values, not indexes.

Think first

  • Which values are candidates for the floor? Where do they sit in a sorted array?
  • When you find a candidate at mid, could there be a better one, and on which side?
  • If x is in the array, what are the floor and the ceil?

Hints

    Brute force, and why it fails

    Scan every value and keep the best floor and ceil: O(n). The sorted order lets two binary searches do it in O(log n).

    The key insight

    The floor is the value just before the upper bound of x, and the ceil is the value at the lower bound. Recording a candidate each time the test passes gives both without extra index checks.

    Dry run

    30lo
    41 
    42 
    73 
    84 
    105hi
    floor-1

    nums = [3, 4, 4, 7, 8, 10] and x = 5. First the floor, the largest value at most 5.

    Step 1 of 4

    The plan

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

    Complexity

    Time
    O(log n)
    Space
    O(1)

    Two binary searches, each O(log n).

    Edge cases

    • x in the array: floor and ceil are both x.
    • x below every value: the floor is -1.
    • x above every value: the ceil is -1.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] getFloorAndCeil(int[] nums, int x) {
            int floor = -1, ceil = -1;
            int lo = 0, hi = nums.length - 1;
            while (lo <= hi) {                      // floor: the last value <= x
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] <= x) { floor = nums[mid]; lo = mid + 1; }   // a candidate; look right for a bigger one
                else hi = mid - 1;
            }
            lo = 0; hi = nums.length - 1;
            while (lo <= hi) {                      // ceil: the first value >= x
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] >= x) { ceil = nums[mid]; hi = mid - 1; }    // a candidate; look left for a smaller one
                else lo = mid + 1;
            }
            return new int[]{floor, ceil};
        }
    }

    C++

    class Solution {
    public:
        vector<int> getFloorAndCeil(vector<int>& nums, int x) {
            int floorV = -1, ceilV = -1;
            int lo = 0, hi = static_cast<int>(nums.size()) - 1;
            while (lo <= hi) {                      // floor: the last value <= x
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] <= x) { floorV = nums[mid]; lo = mid + 1; }   // a candidate; look right
                else hi = mid - 1;
            }
            lo = 0; hi = static_cast<int>(nums.size()) - 1;
            while (lo <= hi) {                      // ceil: the first value >= x
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] >= x) { ceilV = nums[mid]; hi = mid - 1; }    // a candidate; look left
                else lo = mid + 1;
            }
            return {floorV, ceilV};
        }
    };

    Python

    class Solution:
        def getFloorAndCeil(self, nums: list[int], x: int) -> list[int]:
            floor = ceil = -1
            lo, hi = 0, len(nums) - 1
            while lo <= hi:                         # floor: the last value <= x
                mid = (lo + hi) // 2
                if nums[mid] <= x:
                    floor, lo = nums[mid], mid + 1  # a candidate; look right for a bigger one
                else:
                    hi = mid - 1
            lo, hi = 0, len(nums) - 1
            while lo <= hi:                         # ceil: the first value >= x
                mid = (lo + hi) // 2
                if nums[mid] >= x:
                    ceil, hi = nums[mid], mid - 1   # a candidate; look left for a smaller one
                else:
                    lo = mid + 1
            return [floor, ceil]

    Common mistakes

    • Returning indexes instead of values.
    • Using < for the floor or > for the ceil, which misses x itself.
    • Stopping at the first candidate instead of moving on to look for a better one.

    Similar problems