Implement an iterator for a nested list (flatten a nested list of integers)?
Short answer: public class NestedIterator { private Queue<int> queue; public NestedIterator(IList<NestedInteger> nestedList) { queue = new Queue<int>(); Flatten(nestedList); } private void Flatten(IList<NestedInteger> nestedList) { foreach (var ni in nestedList) { if (ni.IsInteger()) queue.Enqueue(ni.GetInteger()); else Flatten(ni.GetList()); } } public bool HasNext() { return queue.Count > 0; } public int Next() { return…
Explain a bit more
queue.Dequeue(); } } Note: NestedInteger is an interface with methods: IsInteger(), GetInteger(), GetList(). Explanation: Pre-flatten the nested list into a queue and iterate over it. Follow on:
Example code
public class NestedIterator {
private Queue<int> queue;
public NestedIterator(IList<NestedInteger> nestedList) {
queue = new Queue<int>(); Flatten(nestedList); }
private void Flatten(IList<NestedInteger> nestedList) {
foreach (var ni in nestedList) {
if (ni.IsInteger()) queue.Enqueue(ni.GetInteger()); else Flatten(ni.GetList()); }
}
public bool HasNext() {
return queue.Count > 0;
}
public int Next() {
return queue.Dequeue();
}
} Note: NestedInteger is an interface with methods: IsInteger(), GetInteger(), GetList(). Explanation: Pre-flatten the nested list into a queue and iterate over it. Follow on:
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png