Lazy Sorted Iterator Over a BST Using O(h) Memory
Last updated: November 29, 2026
Quick Overview
Implement an iterator over a binary search tree that returns keys in ascending order with next() and has_next(), using O(h) memory and amortized O(1) time per call.
0
0
0 solved
Implement an iterator over a binary search tree that returns keys in ascending order with next() and has_next(), using O(h) memory and amortized O(1) time per call.
A Google onsite design-plus-code question about iterating a huge in-memory index without materializing it. The interviewer checks the amortized analysis and whether you can extend it to seek or to merge two iterators.
What the Interviewer Expects
- Keep a stack of the left spine of the unvisited part
- Push the left spine of the right child after each next()
- Explain why next() is amortized O(1)
- Keep memory at O(h)
- Discuss behavior if the tree is modified during iteration
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
- Add a seek(x) that positions the iterator at the first key >= x.
- Merge two BST iterators to list all keys from both trees in order.
- Implement a reverse iterator alongside it.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Constructor takes the BST root. next() returns the next smallest key; has_next() reports whether one remains. Memory O(h). The tree is not modified during iteration....
High-Level Design
The stack always holds the path of nodes whose keys are not yet returned and whose left subtrees are fully done. Initialize by pushing the root and all its left descendants. next() pops the top, whi...