Floor and Ceil in a BST
Pattern: Floor and ceil
Walk down from the root keeping the best floor and ceil seen. A value below the key is a floor candidate, and a better floor would be bigger, so go right. A value above the key is a ceil candidate; go left. An exact match is both.
The problem
Return [floor, ceil] of key in the BST: the largest value at most the key and the smallest value at least the key,
with -1 for one that does not exist. [8, 4, 12, 2, 6, 10, 14] with key 11 gives [10, 12].
Think first
- If a node is below the key, what does it tell you?
- Where could a better floor be?
- When can you stop early?
Hints
Brute force, and why it fails
Collect the inorder and search it: O(n).
The key insight
Every step down either improves one candidate or rules out a subtree, so one path is enough.
Dry run
| floor | 8 |
|---|---|
| ceil | -1 |
BST [8, 4, 12, 2, 6, 10, 14], key 11. 8 < 11: floor 8, go right.
Step 1 of 3
The plan
while n: if n.val == key: return (key, key)
if n.val < key: floor = n.val; n = n.right
else: ceil = n.val; n = n.left
Complexity
- Time
O(h)- Space
O(1)
One path down.
Edge cases
- Key below everything: floor -1.
- Key above everything: ceil -1.
- Key present: both equal it.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> floorCeilOfBST(TreeNode root, int key) {
int floor = -1, ceil = -1;
for (TreeNode n = root; n != null; ) { // walk down, remembering the best on each side
if (n.val == key) return Arrays.asList(key, key);
if (n.val < key) { floor = n.val; n = n.right; } // a candidate floor; look for a bigger one
else { ceil = n.val; n = n.left; } // a candidate ceil; look for a smaller one
}
return Arrays.asList(floor, ceil);
}
}C++
class Solution {
public:
vector<int> floorCeilOfBST(TreeNode* root, int key) {
int fl = -1, ce = -1;
for (TreeNode* n = root; n != NULL; ) { // walk down, remembering the best on each side
if (n->val == key) return vector<int>{key, key};
if (n->val < key) { fl = n->val; n = n->right; } // a candidate floor; look for a bigger one
else { ce = n->val; n = n->left; } // a candidate ceil; look for a smaller one
}
return vector<int>{fl, ce};
}
};Python
class Solution:
def floorCeilOfBST(self, root, key: int) -> list[int]:
floor = ceil = -1
n = root
while n: # walk down, remembering the best on each side
if n.val == key:
return [key, key]
if n.val < key:
floor, n = n.val, n.right # a candidate floor; look for a bigger one
else:
ceil, n = n.val, n.left # a candidate ceil; look for a smaller one
return [floor, ceil]Common mistakes
- Overwriting a candidate with a worse one.
- Forgetting the exact match.