Lazily Flatten Nested Comment Reply Threads Into One Stream
Last updated: November 29, 2026
Quick Overview
Given a nested list where each element is either a comment id or a list of further nested elements, implement an iterator with next() and has_next() that yields the ids in depth-first order. Do not flatten the whole structure up front.
Meta
November 29, 20260
0
0 solved
Given a nested list where each element is either a comment id or a list of further nested elements, implement an iterator with next() and has_next() that yields the ids in depth-first order. Do not flatten the whole structure up front.
Comment threads on Facebook posts nest replies inside replies, and a moderation or export job may need to stream ids in order without materializing everything. Interviewers check that you use an explicit stack of iterators and that has_next correctly skips empty sublists.
What the Interviewer Expects
- Use a stack of iterators instead of eager flattening
- Make has_next responsible for advancing past empty lists
- Keep next and has_next idempotent with a one-item lookahead
- Handle arbitrarily deep nesting without recursion limits
- Explain amortized cost per element
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 add a remove() that deletes the last returned element?
- What if the nested structure is being modified during iteration?
- How would you iterate in reverse order?
- How would you yield (id, depth) pairs?
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 is a list whose items are ints or lists of the same shape.
has_next()may be called any number of times without consuming.next()returns the next int in depth-first order....
High-Level Design
Hold a stack of Python iterators, starting with one over the top-level list. To find the next integer, pull from the top iterator: if it is exhausted, pop it; if it yields a list, push an iterator ove...