RepeatIterator

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-02-20

Problem Statement

Design and implement a RepeatIterator that iterates over a collection of elements and repeats each element a specified number of times before moving to the next. The focus is on object-oriented design, iterator interface compliance, and modularity.


✅ Functional Requirements


1.Initialization
•Input: a collection of elements (e.g., array or list) and a repeat count n.
•Example:
1 2elements = [a, b, c], repeatCount = 3
•The iterator should return: a, a, a, b, b, b, c, c, c.
1.Iterator Interface
•Implement methods:
1 2bool hasNext() 3T next() 4void reset() # Optional: reset to beginning
•hasNext() → Returns true if there are remaining elements.
•next() → Returns the next repeated element.
1.Extensibility
•Support generic types for elements.
•Support dynamic repeat counts for each element (optional extension).


🔐 Constraints & Assumptions


•Input collection is non-empty.
•Repeat count n is a positive integer.
•Iterator should be stateless beyond internal counters, allowing multiple iterators over the same collection.
•Thread-safety is optional unless explicitly required.


🧱 Key Components & Classes


1.RepeatIterator Class
1 2template <typename T> 3class RepeatIterator { 4private: 5 vector<T> elements; // Collection to iterate 6 int repeatCount; // Number of repetitions per element 7 int index; // Current element index 8 int repeatIndex; // How many times current element has been returned 9public: 10 RepeatIterator(vector<T> elems, int n); 11 bool hasNext(); 12 T next(); 13 void reset(); 14};
1.Internal State
•index → Tracks current element in the collection.
•repeatIndex → Tracks how many times current element has been returned.


🔄 Example Workflow


1.Initialize iterator: [1,2,3] with repeat count 2.
2.Call next() → returns 1 → repeatIndex increments.
3.Call next() → returns 1 → repeatIndex reaches repeatCount → index increments.
4.Call next() → returns 2 → repeatIndex reset to 1.
5.Continue until all elements repeated desired times.


🧪 Expected Deliverables


•Class diagram for RepeatIterator.
•Implementation of hasNext(), next(), and optional reset().
•Test cases:
•[a,b] with repeat 3 → output a,a,a,b,b,b.
•Empty collection → hasNext() should return false.
•Single-element collection → repeated correctly.


💡 Discussion Points


•Trade-offs between internal counters vs duplicating elements in a list.
•Memory efficiency: avoid storing repeated elements explicitly.
•Extensibility for different repeat counts per element.
•Compatibility with existing iterator patterns in language (C++, Java, Python).


Solution

Comments