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
Coding & Algorithms
Machine Learning Engineer
Meta
November 29, 2026
Machine Learning Engineer
Onsite
Coding & Algorithms
Hard

0

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
BST
two stacks
predecessor and successor
k-nearest
heap
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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 ...


Submit Your Answer
Markdown supported