Skip to problem
←

Ceiling in a Sorted Array

Easy 0 attempts

You're given a sorted array arr and a value x. Find the ceiling of x in the array — the smallest element that is greater than or equal to x. Return -1 when no such element exists.

Function contract

Implement ceiling(arr, x), where arr is sorted in nondecreasing order and may contain duplicates.

Output: The smallest array value greater than or equal to x, or -1 if no such value exists. Return a value, not an index.

Example 1

Input
arr = [1,2,8,10,10,12,19]
x = 5
Output
8

Example 2

Input
arr = [1,2,8,10]
x = 0
Output
1
Constraints
  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^6
  • 0 <= x <= 10^6
  • arr is sorted in nondecreasing order.

Binary Search

javascript
function ceiling(arr, x) {
  let lo = 0, hi = arr.length - 1, result = -1;
  while (lo <= hi) {
    const mid = (lo + hi) >> 1;
    if (arr[mid] >= x) { result = arr[mid]; hi = mid - 1; }
    else lo = mid + 1;
  }
  return result;
}

Time: O(log n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript