Problem
Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods:
next()
: returns the next element in the array of arrays. If there are no more elements, raise an exception.has_next()
: returns whether or not the iterator still has elements left.
Examples
Example 1
|
|
Similar Problem
Solution
Method 1 - Check the size of the array
To implement a 2D iterator:
- Initialization: Begin by pointing to the first element of the first sub-array. Skip any empty sub-arrays.
next()
method: Return the current element and move the pointer to the next element. If the end of a sub-array is reached, move to the next non-empty sub-array.has_next()
method: Check if there are any more elements left in the 2D array by ensuring the pointers are within valid bounds and not pointing to an empty sub-array.
Approach
- Initialization: Use indices to track the current position within the 2D array.
next()
method: Move the indices forward after returning the current element.has_next()
method: Check the current indices and skip any empty sub-arrays.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
fornext()
since we are only moving indices forward after each call.O(1)
forhas_next()
since the check is done in constant time.
- 🧺 Space complexity:
O(1)
since we are only using a fixed amount of extra space to keep track of indices.
Method 2 -
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(NNNXXXNNN)
- 🧺 Space complexity:
O(NNNXXX)