Calculate Floor & Ceiling

Ceil The Floor

Since the array is sorted, we can use binary search to efficiently find:

  • Floor → greatest number ≤ x.

  • Ceiling → smallest number ≥ x.

Binary search helps narrow down both floor and ceiling in O(log n) time.

Steps

  1. Initialize floor = -1 and ceiling = -1.

  2. Use binary search on the array:

    • If a[mid] == x, both floor and ceiling are x.

    • If a[mid] < x, update floor = a[mid] and move right.

    • If a[mid] > x, update ceiling = a[mid] and move left.

  3. Once the loop ends, return [floor, ceiling].

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(logN)\text{O}(\log{N})

Code

Last updated