Trim a BST of Post IDs to an Allowed ID Range
Last updated: November 29, 2026
Quick Overview
Given a BST of post IDs and bounds [low, high], remove every node outside the range and return the root of the trimmed tree, preserving relative structure.
Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026Software Engineer
Phone Screen
Coding & Algorithms
Easy
0
0
0 solved
Given a BST of post IDs and bounds [low, high], remove every node outside the range and return the root of the trimmed tree, preserving relative structure.
A short Meta phone-screen recursion question. The interviewer looks for the key observation that when a node is out of range, an entire side of it is also out of range and can be skipped without visiting it.
What the Interviewer Expects
- Use BST ordering to skip whole subtrees
- Return the right subtree's trim when node < low
- Return the left subtree's trim when node > high
- Recurse both sides when the node is in range
- State O(n) worst case and O(h) recursion
Key Topics to Cover
BST
recursion
pruning
range queries
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
- Do it iteratively.
- Return the number of removed nodes.
- Trim to a union of two ranges.
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, integers
low <= high. - Output: root of the tree containing exactly the nodes with
low <= val <= high, with ancestor relations among kept nodes preserved....
High-Level Design
At each node:
val < low: the node and its entire left subtree are too small. The answer is the trimmed right subtree.val > high: the node and its entire right subtree are too large. The answe...
Submit Your Answer
Markdown supported