PPractick

DSA interview question

Floor and Ceil in a BST (One Walk)

Easy · Algorithms · Topics: bst, recursion

The problem

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.

Function signature

pair<int, int> floorAndCeil(TreeNode* root, int key);  // {floor, ceil}; -1 when absent

Test cases

Input (tree, key)OutputExplanation
([8,4,12,2,6,10,14], 5)floor 4 ceil 6
([8,4,12,2,6,10,14], 8)floor 8 ceil 8An exact match is both
([8,4,12,2,6,10,14], 1)floor -1 ceil 2Below everything
([8,4,12,2,6,10,14], 15)floor 14 ceil -1Above everything
([8,4,12,2,6,10,14], 11)floor 10 ceil 12

(Confirm: keys are distinct and positive, so −1 can mean "none".)

How interviewers phrase it

Clarifying questions to ask

  1. Floor is the largest ≤ key, and ceil the smallest ≥ key? (Yes.)
  2. What should be returned if none exists? (−1.)
  3. Are keys distinct? (Yes.)

Follow-ups to expect

  1. "Why are both answers on the search path?"
  2. "Why is the last candidate the best?"
  3. "What happens on an exact match?"
  4. "How do these generalise?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in