{x}
blog image

Flatten 2D Vector

Solution Explanation

This problem asks to design an iterator that flattens a 2D vector. The solution involves maintaining pointers (i and j) to track the current row and column within the 2D vector. The next() method returns the next element and advances the pointers, while hasNext() checks if there are more elements to iterate.

The core logic lies in the forward() helper function. This function efficiently moves the pointers to the next valid element. It iterates through the rows, skipping empty or already traversed rows, and resetting the column index (j) when a row is finished.

Time and Space Complexity Analysis

  • Time Complexity:

    • __init__ (constructor): O(1). Initialization takes constant time.
    • next(): O(R) in the worst case, where R is the number of rows. This is because forward() might need to traverse multiple rows if they are empty. However, in an amortized sense, the time complexity is close to O(1) because the pointer advancement happens only once per element.
    • hasNext(): O(R) in the worst case for the same reason as next(). Again, amortized complexity is closer to O(1).
  • Space Complexity: O(1). The solution uses only a constant amount of extra space to store the pointers i and j.

Code Explanation (Python as Example, but the logic is consistent across all languages)

The Python code follows this structure:

  1. __init__(self, vec: List[List[int]]): The constructor initializes the 2D vector (vec), row index (i), and column index (j).

  2. next(self) -> int: This method:

    • Calls forward() to move to the next valid element.
    • Returns the current element (vec[i][j]).
    • Increments the column index (j).
  3. hasNext(self) -> bool: This method:

    • Calls forward() to move to the next valid element.
    • Returns True if there are more elements (i < len(self.vec)), otherwise False.
  4. forward(self): This crucial helper function:

    • Iterates through the rows as long as there are rows (i < len(self.vec)) and the current row is empty or fully traversed (j >= len(self.vec[i])).
    • Increments the row index (i) and resets the column index (j) to 0 for the next row.

The other languages (Java, C++, Go, TypeScript) implement the same logic with their respective syntax and data structures. The key features—the i, j pointers, the forward method, and the overall approach—remain identical.