DSA interview question
A ranking service stores scores in a BST and gets queries like "what's the 3rd lowest score?" and "what's the 3rd highest?". An inorder traversal visits BST keys in ascending order, so the k-th node it visits is the k-th smallest. A reverse inorder traversal (right, node, left) visits keys in descending order, so its k-th node is the k-th largest. An iterative traversal with a stack can stop as soon as it reaches the k-th node instead of traversing everything.
Example: BST [5, 3, 6, 2, 4, null, null, 1], k = 3 → smallest 3, largest 4.
int kthSmallest(TreeNode* root, int k); // 1 <= k <= n
int kthLargest(TreeNode* root, int k);
Input (tree, k) | Output | Explanation |
|---|---|---|
([5, 3, 6, 2, 4, null, null, 1], 3) | smallest 3 largest 4 | Sorted: 1 2 3 4 5 6 |
([5, 3, 6, 2, 4, null, null, 1], 6) | smallest 6 largest 1 | k = n |
([3, 1, 4, null, 2], 1) | smallest 1 largest 4 | |
([3, 1, 4, null, 2], 4) | smallest 4 largest 1 | |
([7], 1) | smallest 7 largest 7 |
(Confirm: 1 ≤ k ≤ number of nodes; keys are distinct.)
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