DSA interview question
A search index keeps data in binary trees and rebalances them when they get lopsided, because deep, skewed trees make lookups slow. A tree is height-balanced when, at every node, the heights of the left and right subtrees differ by at most 1. Checking each node separately recomputes heights over and over (O(n²) on skewed trees). The standard fix computes height bottom-up and returns a sentinel −1 as soon as any subtree is unbalanced, so the check and the height come out of a single O(n) pass.
Example: [3, 9, 20, null, null, 15, 7] → true; [1, 2, 2, 3, 3, null, null, 4, 4] → false.
bool isBalanced(TreeNode* root);
| Input (level order) | Output | Explanation |
|---|---|---|
[3, 9, 20, null, null, 15, 7] | true | |
[1, 2, 2, 3, 3, null, null, 4, 4] | false | The root's subtrees have heights 3 and 1 |
[1, 2, 3, 4] | true | Every difference is at most 1 |
[1, null, 2, null, 3] | false | A chain of three |
[] | true |
(Confirm: the condition applies at every node, not just the root; height counts nodes.)
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