Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.
Implement the Vector2D class:
Vector2D(int[][] vec) initializes the object with the 2D vector vec.next() returns the next element from the 2D vector and moves the pointer one step ahead. You may assume that all calls to next() will be valid.hasNext() returns true if there are still some elements in the vector, and false otherwise.Example 1:
Input ["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"] [[[1, 2], [3], [4]], [], [], [], [], [], [], []] Output [null, 1, 2, 3, true, true, 4, false] Explanation Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]); vector2D.next(); // return 1 vector2D.next(); // return 2 vector2D.next(); // return 3 vector2D.hasNext(); // return true vector2D.hasNext(); // return true vector2D.next(); // return 4 vector2D.hasNext(); // return false
Constraints:
0 <= vec.length <= 2000 <= vec[i].length <= 500-500 <= vec[i][j] <= 500105 calls will be made to next and hasNext.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a nested collection of items, like a book containing chapters, and you need to read through every single item one by one in order. The brute force approach gathers everything beforehand into one single, flat list so you can easily go through them one after another.
Here's how the algorithm would work step-by-step:
class Vector2D:
def __init__(self, vector_two_dimensional):
# Pre-flatten the nested structure to simplify traversal operations later
self.flattened_list = []
for inner_vector in vector_two_dimensional:
for current_item in inner_vector:
self.flattened_list.append(current_item)
self.current_position = 0
def next(self) -> int:
# Retrieve the current item and advance position to prepare for subsequent calls
item_to_return = self.flattened_list[self.current_position]
self.current_position += 1
return item_to_return
def hasNext(self) -> bool:
# Check if the traversal pointer has reached the end of the flattened sequence
return self.current_position < len(self.flattened_list)Instead of combining all the lists into one massive list ahead of time, the optimal strategy keeps track of our exact location using two pointers. One pointer remembers which inner group we are currently visiting, and the other pointer remembers our exact spot inside that group.
Here's how the algorithm would work step-by-step:
class VectorTwoDimensional:
def __init__(self, vector_list: list[list[int]]):
self.vector_data = vector_list
self.outer_pointer = 0
self.inner_pointer = 0
def has_next(self) -> bool:
# Skip empty inner lists to ensure the outer pointer always targets valid data.
while self.outer_pointer < len(self.vector_data) and self.inner_pointer >= len(self.vector_data[self.outer_pointer]):
self.outer_pointer += 1
self.inner_pointer = 0
return self.outer_pointer < len(self.vector_data)
def next(self) -> int:
# Ensure the pointers are correctly positioned before attempting to retrieve an element.
if not self.has_next():
raise IndexError("No more elements available")
current_element = self.vector_data[self.outer_pointer][self.inner_pointer]
self.inner_pointer += 1
return current_element| Case | How to Handle |
|---|---|
| Completely empty 2D vector where the outer list is empty | The outer and inner pointers start at zero and safely skip execution since no elements exist. |
| Outer vector contains only empty inner vectors | The iterator advances the outer pointer past the empty inner lists until it finds a valid element or exhausts the bounds. |
| 2D vector with a single integer in a single inner vector | HasNext returns true once and next returns the element while correctly advancing state to depletion. |
| Extremely skewed input with many empty inner vectors surrounding one populated inner vector | The advance method uses a loop to continuously skip empty inner vectors until reaching a non-empty one. |
| Calling next when no elements remain in the flattened sequence | The method throws a standard out-of-bounds orNoSuchElement exception to signal invalid state. |
| Inputs containing extreme integer values like Integer.MIN_VALUE or Integer.MAX_VALUE | Values are stored and retrieved transparently without arithmetic manipulation, preventing overflow issues. |
| Large scale 2D vectors with deeply nested or massive collections of data | Using lazy evaluation via pointers avoids flattening the entire structure upfront and saves memory. |