DSA interview question
Two shops keep their product IDs in separate BSTs, and a combined catalogue needs all IDs from both trees in sorted order. Each BST's inorder traversal is already sorted, so the task is merging two sorted streams. Materialising both inorder lists and merging works with O(n + m) extra memory. The elegant version runs two iterative inorder traversals in lockstep, each with its own stack, and always advances the one whose next value is smaller. That needs only O(h₁ + h₂) extra memory.
Example: [2, 1, 4] and [1, 0, 3] → [0, 1, 1, 2, 3, 4].
vector<int> getAllElements(TreeNode* root1, TreeNode* root2);
Input (tree1, tree2) | Output | Explanation |
|---|---|---|
([2, 1, 4], [1, 0, 3]) | [0, 1, 1, 2, 3, 4] | |
([1, null, 8], [8, 1]) | [1, 1, 8, 8] | Duplicates across trees are kept |
([], [5, 1, 7]) | [1, 5, 7] | |
([3], []) | [3] | |
([], []) | [] |
(Confirm: each tree is a valid BST; values may repeat across the two trees.)
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