Design a custom iterator for arrays
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2023-09-12
Problem Statement
Design and implement a custom iterator for arrays that allows flexible traversal, supports additional features such as skipping, filtering, or bidirectional iteration, and follows object-oriented principles.
Functional Requirements (FR)
Basic Iteration
•Traverse an array from start to end using next() and hasNext() methods.
•Support retrieving the current element with current() or peek().
Advanced Traversal Features (Optional)
•Bidirectional iteration → Support previous() and hasPrevious().
•Skip functionality → Skip n elements in a single step.
•Filter-based iteration → Iterate only over elements matching a condition.
•Reset iterator → Start iteration from the beginning.
Concurrency (Optional)
•Support thread-safe iteration for read-only arrays.
Non-Functional Requirements (NFR)
•Performance → O(1) for next() and hasNext().
•Extensibility → Easy to add features like filtering, skipping, or transformations.
•Memory Efficiency → Minimal extra memory usage.
Core Entities & Attributes
ArrayIterator<T>
•array[] → Reference to the original array.
•currentIndex → Current position in the array.
•filterFunction (Optional) → Function to filter elements.
•step → Step size for skipping elements.
Optional Classes / Interfaces
•Iterator Interface → Defines standard methods: hasNext(), next(), current().
•Filter / Predicate → Function or interface to filter elements.
Core Components
ArrayIterator Class
•Implements standard iterator methods (next(), hasNext()).
•Supports optional features: skip, filter, bidirectional iteration.
Filter Mechanism
•Accepts a predicate to include only specific elements in iteration.
Concurrency Support (Optional)
•For read-only arrays, synchronize iteration or provide immutable view.
APIs / Operations
Basic Iterator APIs
•hasNext(): boolean → Checks if next element exists.
•next(): T → Returns next element and advances cursor.
•current(): T → Returns current element without advancing.
•reset(): void → Resets iteration to start.
Optional Advanced APIs
•hasPrevious(): boolean → Checks if previous element exists.
•previous(): T → Returns previous element and moves cursor back.
•skip(n: int): void → Skips n elements ahead.
•setFilter(filterFunction: (T) → boolean): void → Apply filter to iteration.
LLD Design Goals
•Class Diagram → ArrayIterator<T> implementing Iterator<T> interface.
Design Patterns:
•Iterator Pattern → Separate traversal logic from the array.
•Decorator / Strategy (Optional) → Apply filtering or skipping behavior dynamically.
•Concurrency Handling (Optional) → Immutable array reference or synchronized methods.
•Trade-offs → 1. Supporting bidirectional or filtered iteration may increase complexity. 2. Extra memory for filtered views vs. on-the-fly filtering.