1627. Bracket the Key
A price ladder is stored as a binary search tree: every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. All keys are distinct and non-negative.
Given the root and an integer target, return a two-element array [floor, ceil]. The floor is the largest key that is less than or equal to target; the ceil is the smallest key that is greater than or equal to target. If no such key exists, use -1 in that position. When target itself is a key, both entries equal target.
Solve it with a single walk from the root downward, remembering the best candidates seen so far, instead of scanning all nodes. Target complexity: O(h) time and O(1) space, where h is the tree height.
Example 1
- Input:
- root = [8,3,10,1,6,null,14], target = 5
- Output:
- [3,6]
- Explanation:
Keys 3 and 6 surround 5, so the floor is 3 and the ceiling is 6.
Example 2
- Input:
- root = [8,3,10,1,6,null,14], target = 8
- Output:
- [8,8]
- Explanation:
Key 8 exists, so it is both floor and ceiling.
Example 3
- Input:
- root = [8,3,10,1,6,null,14], target = 0
- Output:
- [-1,1]
- Explanation:
Nothing is at most 0, so the floor is -1; the smallest key at least 0 is 1.
Constraints
1 ≤ nodes ≤ 1000
0 ≤ key, target ≤ 106
keys are distinct and root is a valid BST
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(h)
- Space
- O(1)