Ceil the Floor Visualization & Animation
Finds both floor and ceil of a target in a single binary search pass over a sorted array.
## What is it?
Find both the floor (largest element ≤ target) and ceil (smallest element ≥ target) of a target value in a sorted array in a single pass using binary search.
## How it works
- Run binary search tracking two candidates: `floor` and `ceil`
- If `arr[mid] == target` → floor = ceil = `arr[mid]`; done
- If `arr[mid] < target` → `arr[mid]` is a floor candidate; update floor, move `low = mid + 1`
- If `arr[mid] > target` → `arr[mid]` is a ceil candidate; update ceil, move `high = mid - 1`
## When to use
- Finding the two closest values to a target in a sorted array
- Interval queries and nearest-neighbor lookups
- Prerequisite for more complex binary search problems
## Key Points
- Both floor and ceil can be found in a single binary search pass
- If target exists in the array, floor == ceil == target
- If target is smaller than all elements, floor does not exist; if larger than all, ceil does not exist
Category: algorithms
Difficulty: beginner
- lower-upper-bound
- binary-search
Time Complexity: O(log n)
Space Complexity: O(1)
View Ceil the Floor VisualizationCeil the Floor
beginnerFinds both floor and ceil of a target in a single binary search pass over a sorted array.
PhaseUpper Bound
x5
Floor—
Ceil—
Round 1 — upper_bound (Floor)
lo
mid
hi
1
[0]2
[1]8
[2]10
[3]10
[4]12
[5]19
[6]mid / ceil candidate
floor candidate / result
too big / too small
search window
Round 1 — upper_bound: lo=0, hi=7. Find first index where arr[i] > x=5.
1 / 19