Trains the technique from
LeetCode 272Closest Binary Search Tree Value IIThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A water utility files every meter reading it has ever taken into a binary search tree keyed by the reading itself: for any filed reading, everything in the branch to its left is smaller and everything in the branch to its right is larger. No two filed readings are the same.
The tree arrives as readings, a level-order listing. Its first entry is the reading at the top of the tree. After that, the listing gives the left branch then the right branch of each reading already listed, in the order those readings appear, writing null where a branch is empty. Slots below a null are never written down, and the trailing run of null entries is left off.
An auditor supplies target, a figure that need not be a whole number and may fall outside the range of the filed readings, and asks for the k readings nearest to it. Rank the filed readings by the size of the gap |reading - target|, smallest gap first; when two readings sit at exactly the same gap, the smaller reading ranks first. Take the first k readings of that ranking.
Return those k readings in ascending order. You are told that k never exceeds the number of filed readings.
Example 1
The filed readings are 4, 9, 14, 20, 27, 35 and 41, with gaps to 15 of 11, 6, 1, 5, 12, 20 and 26. The three smallest gaps belong to 14, 20 and 9, which come back in ascending order.
Example 2
Gaps to 25 are 25, 15, 5, 5 and 15 for readings 50, 40, 30, 20 and 10. Readings 20 and 30 take the first two places at a gap of 5, and the third place is contested at a gap of 15 by 10 and 40, where the smaller reading 10 ranks first.
Example 3
Readings 30 and 40 both sit 5 away from 35, and the smaller of two equally close readings ranks first, so the single answer is 30.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def nearest_readings(readings: list[int | None], target: float, k: int) -> list[int]:public List<Integer> nearestReadings(Integer[] readings, double target, int k)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.