Taro Logo

Flatten 2D Vector

#5 Most AskedMedium
1 view
Topics:
Arrays

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 <= 200
  • 0 <= vec[i].length <= 500
  • -500 <= vec[i][j] <= 500
  • At most 105 calls will be made to next and hasNext.

Solution


Clarifying Questions

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:

  1. Can the 2D vector contain empty inner vectors (e.g., `[[], [1, 2], [], [3]]`), and how should our iterator handle them?
  2. What should happen if `next()` is called when there are no more elements left in the iterator?
  3. Should the iterator support the optional `remove()` operation, or do we only need to implement `next()` and `hasNext()`?
  4. Will the input 2D vector be modified while the iterator is being used, or can we assume it is immutable during traversal?
  5. What data types are the elements in the vector, and are we allowed to use extra space to flatten the vector entirely during initialization, or should we do it lazily to optimize space?

Brute Force Solution

Approach

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:

  1. Start by looking at the entire collection of grouped items.
  2. Go through each group one by one, starting from the very first group.
  3. Take every single item out of the current group and copy it into a brand new, single continuous line of items.
  4. Repeat this gathering process for the second group, the third group, and so on, until every single item from every group has been copied over.
  5. Once all the items are sitting in this one long line, you are done preparing the data.
  6. To answer any questions about whether there are more items left or to read the next item, simply walk down this new long line from the very beginning to the very end.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(N) – The time complexity is driven by flattening all the elements across the nested groups into a single continuous list during initialization. If we let N be the total number of elements across all groups, the preprocessing step visits every single element once to copy it over. Afterwards, the `next` and `hasNext` operations take constant O(1) time since they just iterate through this pre-built single list. Therefore, the total operations for the initialization scale linearly with the total number of elements, approximating N operations in total and simplifying to O(N).
Space Complexity
O(N) – The brute force approach described in the steps copies every single item from the nested collection into a brand new, single continuous line of items. If we define N as the total number of elements across all groups, this new flat list requires an auxiliary data structure proportional in size to N. Therefore, the extra memory used scales linearly with the total number of elements, resulting in an overall space complexity of O(N).

Optimal Solution

Approach

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:

  1. When asked for the next item, check if our current group still has unvisited items remaining.
  2. If the current group is empty or we have finished looking at everything inside it, move our group pointer forward to the next available group.
  3. Repeat the group-shifting step until we find a group that actually has items left, or until we run out of groups entirely.
  4. Once we are securely positioned inside a group with available items, grab the item at our current spot.
  5. Advance our inner spot pointer so we do not look at the same item twice.
  6. When asked if any items remain, simply check if our group pointer has successfully found a valid item to look at.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(1) per hasNext() and next() call, and O(V + K) for initialization where V is the total number of vectors and K is the total number of integers – During initialization, we store the 2D vector reference. The hasNext() and next() methods advance our two pointers through the inner and outer lists without ever revisiting elements. Each integer across all vectors is visited at most once across the lifetime of the iterator. Across all N total calls to next(), the total work simplifies to amortized O(1) time per element.
Space Complexity
O(1) – The algorithm maintains only two integer pointers to track the current group and the exact spot inside that group, without pre-flattening or copying any input data. Regardless of the total number of elements across all lists, these scalar state variables require a constant amount of extra memory. Therefore, the auxiliary space complexity remains strictly constant at O(1) beyond the input itself.

Edge Cases

Completely empty 2D vector where the outer list is empty
How to Handle:
The outer and inner pointers start at zero and safely skip execution since no elements exist.
Outer vector contains only empty inner vectors
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Values are stored and retrieved transparently without arithmetic manipulation, preventing overflow issues.
Large scale 2D vectors with deeply nested or massive collections of data
How to Handle:
Using lazy evaluation via pointers avoids flattening the entire structure upfront and saves memory.
0/21 completed