LeetCode 251: Flatten 2D Vector

Problem Description

Explanation:

To flatten a 2D vector, we can implement an iterator that iterates over each element in the 2D vector in a flattened manner. We can achieve this by using two indices, row and col, to keep track of the current position in the 2D vector.

Algorithm:

  1. Initialize row and col to 0.
  2. In the next() function, return the element at row, col position.
  3. In the hasNext() function, check if there are more elements left in the 2D vector.
  4. If col reaches the end of the current row, increment row and reset col to 0.
  5. Repeat steps 2-4 until all elements are visited.

Time Complexity:

  • next() and hasNext() functions will take O(1) time on average.

Space Complexity:

  • O(1) as we are not using any extra data structures. :

Solutions

class Vector2D {
    int[][] vec2d;
    int row;
    int col;

    public Vector2D(int[][] vec) {
        vec2d = vec;
        row = 0;
        col = 0;
    }

    public int next() {
        hasNext();
        return vec2d[row][col++];
    }

    public boolean hasNext() {
        while (row < vec2d.length && col == vec2d[row].length) {
            row++;
            col = 0;
        }
        return row < vec2d.length;
    }
}

Loading editor...