Lazy In-Order Iterator Over a BST of Post Timestamps
Last updated: November 29, 2026
Quick Overview
Implement an iterator over a BST of post timestamps with next() returning the next smallest timestamp and has_next(), using O(h) memory.
Meta
November 29, 20260
0
0 solved
Implement an iterator over a BST of post timestamps with next() returning the next smallest timestamp and has_next(), using O(h) memory.
A frequent Meta onsite question about iterator design, framed around paging through an index of posts. Interviewers expect amortized O(1) next() with O(h) memory and an explanation of why the amortized bound holds.
What the Interviewer Expects
- Avoid flattening the whole tree upfront
- Keep a stack of the leftmost path
- On next(), pop and push the left spine of the right child
- Explain amortized O(1) per call
- Keep memory O(h)
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 peek() method.
- Support a reverse iterator as well.
- How would you make the iterator safe if the tree is modified during iteration?
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 root.
next()returns the next smallest value; called only whenhas_next()is true.has_next()in O(1).- Memory O(h), not O(n)....
High-Level Design
Take the iterative in-order traversal and split it across calls. The stack always holds the path of nodes whose left subtrees are done but which themselves have not been returned.
- Constructor: push...