Find the K Stored Timestamps Closest to a Target in a BST

Last updated: November 29, 2026

Quick Overview

A binary search tree stores timestamps of indexed events. Given a target time and k, return the k stored values closest to the target, in any order.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


A binary search tree stores timestamps of indexed events. Given a target time and k, return the k stored values closest to the target, in any order.

A Google onsite hard question in a Search indexing flavor: find the k events nearest a query time. The O(n) in-order sliding window is the baseline; the interviewer pushes for two iterators (predecessor and successor stacks) to reach O(h + k).

What the Interviewer Expects
  • Give the O(n) in-order window baseline
  • Build a predecessor stack and a successor stack from the target
  • Merge outward like two pointers, picking the closer side each step
  • Advance each stack in amortized O(1)
  • State O(h + k) time and O(h) space
Key Topics to Cover
binary search tree
two pointers
iterators
k nearest
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 k is close to n?
  • Return the values in sorted order.
  • How would you answer this if the tree supported rank queries?
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 with unique integer values, float target, and 1 <= k <= n. Output: list of k values with the smallest absolute differences to the target. Ties may be broken either way....

High-Level Design

Initialize two stacks by searching for the target: nodes with value <= target go on the predecessor stack (then go right), and nodes with value > target go on the successor stack (then go left). The t...


Submit Your Answer
Markdown supported