1640. Nearest K Keys
A street of shops is organised as a binary search tree keyed by street number. Given root, an integer target and an integer k, find the k shops whose numbers are closest to target, where closeness is the absolute difference |key - target|. If two keys are equally close, the smaller key counts as closer.
Return those k keys as an int[] sorted in ascending order. All keys are distinct and k never exceeds the number of nodes. Differences can exceed the 32-bit range, so compute them in 64-bit arithmetic.
Aim for O(n) time and O(n) space. Use an iterative traversal so that a degenerate tree cannot overflow the call stack.
Example 1
- Input:
- root = [8,4,12,2,6,10,14], target = 9, k = 3
- Output:
- [6,8,10]
- Explanation:
Keys 8 and 10 are at distance 1 and 6 and 12 tie at distance 3; the smaller key 6 wins, so the answer is 6, 8, 10.
Example 2
- Input:
- root = [5], target = 100, k = 1
- Output:
- [5]
- Explanation:
There is a single key, so it is returned.
Example 3
- Input:
- root = [6,2,9,null,4], target = 5, k = 2
- Output:
- [4,6]
- Explanation:
Keys 4 and 6 are both at distance 1 from the target 5.
Constraints
1 ≤ k ≤ nodes ≤ 1000
keys distinct
-109 ≤ keys, target ≤ 109 (use 64-bit distances)
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(n)
- Space
- O(n)