Prepin
Log in

Create an iterator.

Approach / Explanation

This prompt asks you to create an iterator in your chosen programming language. In computer science, an iterator is a design pattern that facilitates sequential access to elements in a collection while keeping the details of the collection hidden. Typically, an iterator includes two methods: hasNext() , which determines if there is a subsequent element, and next() , which retrieves the next element. It’s crucial to inquire about additional specifics, such as whether the data structure to be iterated over is an array, linked list, or tree, as well as any particular constraints that may apply. Please ensure that your code properly addresses edge cases.

Suggested Answer

In this instance, we will create a Python iterator for a basic list: class MyIterator : def __init__ ( self , data ) : self . index = 0 self . data = data def __iter__ ( self ) : return self def __next__ ( self ) : if self . index < len ( self . data ) : result = self . data [ self . index ] self . index += 1 return result else : raise StopIteration # Testing my_iter = MyIterator ( [ 1 , 2 , 3 , 4 ] ) for item in my_iter : print ( item ) This code defines the class MyIterator , which accepts a list as an input and sets the initial index to 0. It implements the __next__() method to manage the iteration process. When the end of the data is reached, it raises a StopIteration exception, adhering to the iterator protocol in Python.

Alternative Answer

In this example, let's create a Java iterator for an array: import java . util . NoSuchElementException ; public class MyArrayIterator { private int [ ] array ; private int position = 0 ; public MyArrayIterator ( int [ ] array ) { this . array = array ; } public boolean hasNext ( ) { return position < array . length ; } public int next ( ) { if ( ! hasNext ( ) ) throw new NoSuchElementException ( ) ; return array [ position ++ ] ; } } // Testing public static void main ( String [ ] args ) { MyArrayIterator iterator = new MyArrayIterator ( new int [ ] { 1 , 2 , 3 , 4 } ) ; while ( iterator . hasNext ( ) ) { System . out . println ( iterator . next ( ) ) ; } } This Java code defines a class called MyArrayIterator that includes a constructor accepting an array and a mechanism to keep track of the current index. It features the hasNext() method to determine if there's an additional element to iterate over, and the next() method to retrieve the next element. If no elements remain, next() will throw a NoSuchElementException .

Question Details

Difficulty & Category

Medium
algorithms

Companies

Apple

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.