DSA interview question
A price-matching engine stores available price points in a BST. For a customer's target price, it needs the floor (the largest price ≤ target) and the ceil (the smallest price ≥ target), or −1 where none exists. Both candidates lie on the search path for the target. Walking down as if searching, every node with value ≤ target is a better floor than any seen before, and every node with value ≥ target is a better ceil. So a single walk produces both answers.
Example: BST [8, 4, 12, 2, 6, 10, 14], target 5 → floor 4, ceil 6.
pair<int, int> floorAndCeil(TreeNode* root, int key); // {floor, ceil}; -1 when absent
Input (tree, key) | Output | Explanation |
|---|---|---|
([8,4,12,2,6,10,14], 5) | floor 4 ceil 6 | |
([8,4,12,2,6,10,14], 8) | floor 8 ceil 8 | An exact match is both |
([8,4,12,2,6,10,14], 1) | floor -1 ceil 2 | Below everything |
([8,4,12,2,6,10,14], 15) | floor 14 ceil -1 | Above everything |
([8,4,12,2,6,10,14], 11) | floor 10 ceil 12 |
(Confirm: keys are distinct and positive, so −1 can mean "none".)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in