K Stored Scores in a BST Closest to a Target Value
Last updated: November 29, 2026
Quick Overview
Given a BST of ranking scores, a real-valued target, and k, return the k values closest to the target, ideally in O(h + k) time.
Meta
November 29, 20260
0
0 solved
Given a BST of ranking scores, a real-valued target, and k, return the k values closest to the target, ideally in O(h + k) time.
A Meta onsite hard question that extends the single closest value problem. The interviewer expects you to move beyond O(n) traversal to two stacks (predecessors and successors) that expand outward from the target like a merge.
What the Interviewer Expects
- Give the O(n log k) traversal with a max-heap first
- Seed predecessor and successor stacks along the search path
- Advance whichever side is closer, k times
- Explain O(h + k) time
- Handle when one side runs out
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if the tree is not balanced and h is large?
- Return the values sorted by distance.
- What if many queries hit the same tree with different targets?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: BST root (distinct values), float target,
1 <= k <= n. - Output: any order of the k values with smallest
|value - target|....
High-Level Design
Baseline: in-order traversal keeping a max-heap of size k by distance, O(n log k). Or use the sorted in-order list and a sliding window.
O(h + k): the k closest values are a contiguous block ...