Alternate Iterator for List of Lists

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-02-08

Problem Statement

Design and implement an Alternate Iterator that takes as input a collection of lists of integers and allows iteration over them in a round-robin fashion (instead of consuming one list fully before moving to the next).


For example, if the input is:

1 2[ 3 [1, 2, 3], 4 [4, 5], 5 [6, 7, 8, 9] 6]


The iterator should return elements in the following order:

1 21, 4, 6, 2, 5, 7, 3, 8, 9


Functional Requirements


1.Initialization
•Accept a List<List<Integer>> (or equivalent structure) as input.
2.Iteration
•Provide hasNext() method → returns true if there are still elements left.
•Provide next() method → returns the next element in round-robin fashion.
3.Order of Traversal
•Fetch elements cyclically from each non-empty list.
•Skip lists that are exhausted.
4.Edge Cases
•Empty outer list ([]).
•Inner lists may be empty ([[], [1,2], []]).
•Large nested lists should still perform efficiently.


Non-Functional Requirements


•Time Complexity: Each next() and hasNext() should be O(1) amortized.
•Space Complexity: O(k), where k = number of non-empty lists (tracking iterators).
•Clean API: Should behave like a standard iterator (fail-safe in iteration).


Class Design (Example in Java-like Pseudocode)

1 2class AlternateIterator { 3 Queue<Iterator<Integer>> queue; 4 5 AlternateIterator(List<List<Integer>> input) { 6 queue = new LinkedList<>(); 7 for (List<Integer> list : input) { 8 if (!list.isEmpty()) { 9 queue.add(list.iterator()); 10 } 11 } 12 } 13 14 boolean hasNext() { 15 return !queue.isEmpty(); 16 } 17 18 int next() { 19 if (!hasNext()) throw new NoSuchElementException(); 20 Iterator<Integer> curr = queue.poll(); 21 int value = curr.next(); 22 if (curr.hasNext()) { 23 queue.add(curr); // put it back for next round 24 } 25 return value; 26 } 27}


Key Discussion Points in an LLD Round


•How to maintain state across multiple lists? (Queue of iterators).
•How to handle empty lists gracefully?
•How to ensure fairness (round-robin scheduling)?
•Thread-Safety Consideration: If multiple consumers use the same iterator, do we need synchronization?
•Extensibility: What if we want to generalize this to List<Iterator<T>> instead of only integers?


👉 This is a great LLD + coding + discussion

Solution

Comments