Design and Implement a 2D List Iterator
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-07-11
Problem Statement
Design and implement a custom iterator that can iterate through a 2D list (matrix) of integers in row-major order. The iterator should expose the following methods:
1.<span></span>next() → Returns the next element in the iteration.
2.<span></span>hasNext() → Returns whether there are more elements left to iterate.
3.<span></span>remove() → Removes the last element returned by next() from the underlying data structure.
✅ Functional Requirements
1.<span></span>Initialization
2.<span></span>Accept a 2D list (e.g., [[1,2],[3],[4,5,6]]).
3.<span></span>Iteration
4.<span></span>next() should return elements in row-major order: 1,2,3,4,5,6.
5.<span></span>hasNext() should return true if at least one element remains.
6.<span></span>Modification
7.<span></span>remove() should remove the last returned element from the 2D list.
8.<span></span>Must handle consecutive calls to remove() properly (can’t remove twice without calling next()).
9.<span></span>Edge Cases
10.<span></span>Handle empty rows ([[],[1,2],[],[3]]).
11.<span></span>Handle an empty 2D list ([]).
12.<span></span>Handle calling next() when no elements remain (throw exception or return null).
⚙️ Non-Functional Requirements
1.<span></span>Implementation should be object-oriented.
2.<span></span>Must work efficiently in O(1) amortized per operation.
3.<span></span>Should not flatten the entire 2D list upfront (to save memory for large inputs).
🔐 Constraints
1.<span></span>Input size: up to 10^5 total elements.
2.<span></span>Supports only integer values (but design should allow easy extension to generics).
3.<span></span>remove() should be optional but must be implemented cleanly.
🧱 Key Classes / Interfaces
1.<span></span>TwoDListIterator
2.<span></span>constructor(vector<vector<int>> data)
3.<span></span>bool hasNext()
4.<span></span>int next()
5.<span></span>void remove()
🧪 Example Flow
<div><div><br /></div><div>Input: [[1,2],[3],[4,5,6]]</div><div><br /></div><div>Iterator.next() → 1 </div><div>Iterator.next() → 2 </div><div>Iterator.remove() → removes 2 from the structure </div><div>Iterator.next() → 3 </div><div>Iterator.hasNext() → true </div><div>Iterator.next() → 4 </div><div>Iterator.next() → 5 </div><div>Iterator.next() → 6 </div><div>Iterator.hasNext() → false </div></div>👉 This LLD problem tests:
1.<span></span>Iterator design pattern
2.<span></span>Encapsulation of iteration state (row, col pointers)
3.<span></span>Edge case handling (empty rows, remove semantics)
4.<span></span>Efficiency vs memory trade-offs