Find the Floor and Ceiling of a Number in a Sorted Array
Implement floorCeil
Given an array
nums sorted in non-decreasing order and an integer target, return [floor, ceil] — the largest value ≤ target and the smallest value ≥ target. Use -1 for either one if it doesn't exist.
Solve it in O(log n) time: as the binary search narrows in on target, every comparison either tightens the floor or the ceiling, so a single pass finds both.
Example 1:
Input: nums = [1,2,8,10,10,12,19], target = 5
Output: [2,8]
Example 2:
Input: nums = [1,2,8,10,10,12,19], target = 10
Output: [10,10]
Example 3:
Input: nums = [1,8,10], target = 5
Output: [1,8]
+ 4 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 10⁴ - ●
0 ≤ nums[i] ≤ 10⁵ (all values non-negative, so -1 unambiguously means "none") - ●
-10⁵ ≤ target ≤ 10⁵ - ●
nums is sorted in non-decreasing order (duplicates are allowed)
nums =
[1, 2, 8, 10, 10, 12, 19]
target =
5