Interleaving 2D Iterator

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-03-23

Problem Statement

Design a class that iterates over multiple lists (2D input) in a round-robin interleaved order. This iterator should return elements one by one by cycling through each inner list, skipping empty ones dynamically.


This problem is useful in real systems such as multi-source data streaming, task schedulers, or round-robin execution of jobs.


Functional Requirements


1.Input
•A list of lists (List<List<Integer>> or equivalent).
•Example: [[1,2,3], [4,5], [6,7,8,9]].
2.Iteration Behavior
•The iterator should return elements in interleaving order:
•Example above → 1, 4, 6, 2, 5, 7, 3, 8, 9.
•Once a sublist is exhausted, it should be skipped.
3.APIs
•boolean hasNext() → returns true if any list still has remaining elements.
•int next() → returns the next element in round-robin order.
4.Edge Cases
•Some sublists may be empty initially → skip them.
•Only one list is non-empty → behaves like a normal iterator.
•All lists empty → hasNext() should be false, and next() should throw exception.


Non-Functional Requirements


•Time Complexity: Each next() and hasNext() should run in amortized O(1).
•Space Complexity: Should use O(k) extra space where k is the number of lists.
•Extensibility: Should be possible to extend this to N lists, not just 2.
•Thread Safety (optional extension): Multiple consumers could iterate concurrently.


Design Hints for Interview


•You may use a Queue of Iterators approach:
•Push all non-empty iterators into a queue.
•On next(): poll from queue, get element, if more remain → push back.
•Core classes/interfaces:
•InterleavingIterator (implements Iterator<T>).
•List<Iterator<T>> or Queue<Iterator<T>>.


Example Walkthrough

1 2Input: 3 [[1,2,3], [4,5], [6,7,8,9]] 4 5Steps: 6 hasNext() → true 7 next() → 1 8 next() → 4 9 next() → 6 10 next() → 2 11 next() → 5 12 next() → 7 13 next() → 3 14 next() → 8 15 next() → 9 16 hasNext() → false


👉 This is a classic LLD / coding design problem because it checks iterator design, clean abstraction, use of queues, edge case handling, and extensibility.

Solution

Comments