Floor and Ceil in Sorted Array
EasyLargest ≤ x and smallest ≥ x
Floor is the biggest value not over x; ceil is the smallest value not under x — one halving search finds both.
The idea
Floor is the biggest value not exceeding x; ceil is the smallest value not below x. One binary search tracks both as it narrows.
3
4
4
7
8
10
0
1
2
3
4
5
x5
Step 1 of 8. Brute force: scan everything, tracking floor (≤ 5) and ceil (≥ 5). Values: 3, 4, 4, 7, 8, 10. x 5.
1/8
Brute force
timeO(n)spaceO(1)
Scan tracking both.
1for (let i = 0; i < n; i++) {2 if (nums[i] <= x) floor = nums[i];3 if (nums[i] >= x && ceil < 0) ceil = nums[i];4}Input
- array
- [3, 4, 4, 7, 8, 10]
Memory
- i
- —
- x
- 5
- floor
- —
Output
- ceil
- —
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- nums = [3, 4, 4, 7, 8, 10], x = 5
- Output:
- [4, 7]
- Explanation:
- Floor 4 (<=5), ceil 7 (>=5).
Example 2
- Input:
- nums = [3, 4, 4, 7, 8, 10], x = 4
- Output:
- [4, 4]
- Explanation:
- Both floor and ceil are 4.
Example 3
- Input:
- nums = [3, 4, 4, 7, 8, 10], x = 11
- Output:
- [10, -1]
- Explanation:
- No ceil above 11 → -1.
Practice this problem:GeeksforGeeks · floor(opens in a new tab)GeeksforGeeks · ceil(opens in a new tab)
Finished the walkthrough? Add it to your streak.