← Questions
Range sum of a BST
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Oct 2025. It tests binary search tree and dfs.
Given the root of a binary search tree and a range [low, high], return the sum of the node values that fall inside the range, inclusive.
Interface
Unless you agree on a different interface with the interviewer, assume:
range_sum_bst(root: TreeNode | None, low: int, high: int) -> int
Example
10
/ \
5 15
/ \ \
3 7 18
range_sum_bst(root, 7, 15) -> 32 # 7 + 10 + 15
range_sum_bst(root, 6, 10) -> 17 # 7 + 10
Constraints
- Up to
2 * 10^4nodes. Values are distinct. -
low <= high.
Clarifying questions
- Are the bounds inclusive?
- Are the values distinct?
- Is it a single query, or many queries on the same tree?
- Could the tree be very unbalanced?
What a strong answer covers
- A traversal that uses the BST order to skip subtrees: if a node's value is below
low, skip its left subtree; if it is abovehigh, skip its right subtree. - O(n) worst case, and closer to O(h + m) when the range holds
mnodes. O(h) stack, or an iterative version. - Tests: an empty tree, a range that holds no node, a range that holds every node, a range on a single value.
Follow-ups
- Return the average of the values in the range instead of the sum. (Range
[7, 15]gives32 / 3.) - The tree is very large and you answer many queries with different ranges. Precompute an in-order array with prefix sums for O(log n) per query, or store the subtree sum in every node.
- The tree also gets inserts and deletes between queries. Which structure keeps both fast?
Where it's asked
- Meta · Technical phone screen · Last asked Oct 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
binary search tree · dfs
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
