Total Ad Spend for Campaign IDs Within a Range in a BST
Last updated: November 29, 2026
Quick Overview
Campaigns are stored in a binary search tree keyed by campaign ID, and each node's value is that campaign's spend. Return the total spend of campaigns whose IDs lie in an inclusive range [lo, hi].
0
0
0 solved
Campaigns are stored in a binary search tree keyed by campaign ID, and each node's value is that campaign's spend. Return the total spend of campaigns whose IDs lie in an inclusive range [lo, hi].
A Google Ads flavored warm-up that checks whether you use the BST ordering to skip whole subtrees. A plain full traversal is accepted but the interviewer expects you to prune and explain why that helps.
What the Interviewer Expects
- Use BST ordering to skip subtrees outside the range
- Explain the pruning rule for each side
- Give the O(h + k) intuition where k is nodes in range
- Write an iterative version
- Handle an empty range or empty tree
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you answer many range queries quickly on a static tree?
- What if spend values change frequently?
- Return the count of campaigns in range in O(h) if each node stores subtree sizes.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: BST root where each node has a unique integer key and a non-negative val, plus bounds lo <= hi. Output: sum of val for nodes with lo <= key <= hi. Empty tree returns 0....
High-Level Design
At a node with key k: if k < lo, the whole left subtree is smaller too, so only explore the right. If k > hi, only explore the left. Otherwise include the node and explore both sides. This visits node...