DSA interview question
A data-quality tool scans a binary tree that is supposed to be a BST but has been corrupted in places, and it reports the largest subtree that is still a valid BST (counting nodes), so that part can be salvaged. Checking every subtree separately is O(n²). A single post-order pass does it in O(n). Each node gets from its children whether they're BSTs, their sizes, and their minimum and maximum keys. The node forms a BST exactly when both children do and left max < node < right min.
Example: [10, 5, 15, 1, 8, null, 7] → 3 (the subtree 5, 1, 8).
int largestBST(TreeNode* root); // number of nodes in the largest BST subtree
| Input (level order) | Output | Explanation |
|---|---|---|
[10, 5, 15, 1, 8, null, 7] | 3 | 7 under 15 breaks the right side |
[5, 2, 4, 1, 3] | 3 | 4 is on the right of 5 but smaller |
[3, 1, 5, 0, 2, 4, 6] | 7 | The whole tree |
[1] | 1 | |
[] | 0 |
(Confirm: a subtree means a node with all its descendants; BST ordering is strict.)
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