BST Iterator Design in DSA Rust - Time & Space Complexity
We want to understand how fast the BST Iterator works when we use it to get the next smallest value.
How does the time to get the next value change as the tree grows bigger?
Analyze the time complexity of the following code snippet.
struct BSTIterator {
stack: Vec<TreeNode>,
}
impl BSTIterator {
fn new(root: Option<Box<TreeNode>>) -> Self {
let mut it = BSTIterator { stack: Vec::new() };
it.push_left(root);
it
}
fn push_left(&mut self, mut node: Option<Box<TreeNode>>) {
while let Some(n) = node {
let mut tree_node = *n;
let left = tree_node.left.take();
self.stack.push(tree_node);
node = left;
}
}
fn next(&mut self) -> i32 {
let node = self.stack.pop().unwrap();
self.push_left(node.right);
node.val
}
fn has_next(&self) -> bool {
!self.stack.is_empty()
}
}
This code creates an iterator over a binary search tree that returns the next smallest value each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop inside
push_leftthat pushes left children onto the stack. - How many times: Each node is pushed and popped exactly once during the entire iteration.
Getting the next value usually takes a small number of steps, but sometimes it takes more when moving down the left side of a subtree.
| Input Size (n) | Approx. Operations per next() |
|---|---|
| 10 | About 1 to 3 steps |
| 100 | About 1 to 7 steps |
| 1000 | About 1 to 10 steps |
Pattern observation: Most calls to next() do a quick pop, but some do extra work pushing left children. Over all calls, work spreads evenly.
Time Complexity: O(1) amortized
This means each call to next() takes constant time on average, even if some calls take longer.
[X] Wrong: "Each call to next() always takes time proportional to the tree height."
[OK] Correct: Because the extra work of pushing left children is spread out over many calls, so on average each call is fast.
Understanding this amortized time complexity shows you can analyze how repeated operations share work over time, a key skill in coding interviews.
What if we changed the iterator to store all nodes in a sorted list at the start? How would the time complexity of next() change?
Practice
BST Iterator in the context of a Binary Search Tree?Solution
Step 1: Understand BST Iterator functionality
A BST Iterator is designed to traverse the tree in sorted order, typically ascending, without using recursion.Step 2: Identify the main purpose
It provides a way to get the next smallest element efficiently, which matches To traverse the BST in ascending order without recursion.Final Answer:
To traverse the BST in ascending order without recursion -> Option AQuick Check:
BST Iterator = Ascending traversal [OK]
- Confusing iterator with insertion or deletion
- Thinking it balances the tree
- Assuming it uses recursion internally
Solution
Step 1: Understand ownership in Rust for tree nodes
Tree nodes are usually boxed to allow recursive types. The iterator needs ownership or mutable access, so usingVecis correct.Step 2: Analyze options
struct BSTIterator { stack: Vec } usesVec, which is correct. struct BSTIterator { stack: Vec<TreeNode> } usesVec<TreeNode>which is invalid due to recursive type size. struct BSTIterator { stack: Vec<&TreeNode> } uses references which complicate lifetimes. struct BSTIterator { stack: Vec> } usesOptionunnecessarily.Final Answer:
struct BSTIterator { stack: Vec } -> Option DQuick Check:
Use Box for recursive nodes in Vec [OK]
- Using Vec<TreeNode> causes size errors
- Using references without lifetimes
- Wrapping nodes in Option unnecessarily
next() twice?let mut iter = BSTIterator::new(root);
println!("{}", iter.next().unwrap());
println!("{}", iter.next().unwrap());Assuming the BST contains nodes with values 3, 7, 9 in sorted order.
Solution
Step 1: Understand BST Iterator traversal order
The iterator returns nodes in ascending order: 3, then 7, then 9.Step 2: Trace the two next() calls
First next() returns 3, second next() returns 7.Final Answer:
3 7 -> Option CQuick Check:
Next returns ascending values [OK]
- Assuming next() returns largest first
- Mixing up order of traversal
- Ignoring unwrap() usage
next() method:fn next(&mut self) -> Option<i32> {
let node = self.stack.pop()?;
let val = node.val;
let mut current = node.right;
while let Some(n) = current {
self.stack.push(n);
current = n.left;
}
Some(val)
}What is the bug in this code?
Solution
Step 1: Analyze node pushing order in while loop
The code pushes nodes while moving left, but it pushes current node before going left, which reverses order and breaks in-order traversal.Step 2: Identify correct pushing order
Nodes should be pushed starting from leftmost node upwards, so pushing before moving left causes wrong order.Final Answer:
It pushes nodes in wrong order causing incorrect traversal -> Option AQuick Check:
Push left nodes in correct order [OK]
- Ignoring order of stack pushes
- Assuming pop handles empty stack safely
- Confusing ownership with traversal logic
peek() to see the next smallest element without advancing the iterator. Which approach is best to implement peek() efficiently?Solution
Step 1: Understand peek() requirement
Peek should return next smallest element without moving iterator forward, so it needs to know next element in advance.Step 2: Evaluate approaches
Store the next smallest element in a variable updated on eachnext()call keeps next element cached and updates it on next(), making peek() O(1). Traverse the entire BST and store all elements in a vector upfront uses extra memory and upfront cost. Use recursion insidepeek()to find the next element every time is inefficient due to repeated traversal. Modify the BST structure to add parent pointers for easy access complicates BST unnecessarily.Final Answer:
Store the next smallest element in a variable updated on each next() call -> Option BQuick Check:
Cache next element for O(1) peek [OK]
- Recomputing next element on every peek
- Storing entire traversal upfront wasting memory
- Changing BST structure unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
