Similar Problems

Similar Problems not available

Flatten 2d Vector - Leetcode Solution

Companies:

LeetCode:  Flatten 2d Vector Leetcode Solution

Difficulty: Medium

Topics: design array two-pointers  

Problem Statement:

Implement an iterator to flatten a 2D vector. The 2D vector is represented by a vector of vectors and the iterator behaves like an iterator to a 1D vector.

Example:

Input: vector = [[1,2],[3],[4,5,6]]

Output: [1,2,3,4,5,6]

Solution:

The easiest way to flatten a 2D vector is to store all the elements in a single 1D vector. Then we can easily iterate over the 1D vector using a standard iterator.

For this approach, we need to initialize the 1D vector using the elements of the 2D vector. We can do this using nested loops, where the outer loop iterates over all the rows of the 2D vector and the inner loop iterates over all the elements of each row. We can then append each element to the 1D vector.

Now that we have a 1D vector, we can implement the standard iterator using two variables: index and size. The index variable tracks the current position of the iterator, and the size variable keeps track of the total size of the 1D vector.

Whenever the hasNext() function is called, we simply need to check if the index variable is less than the size variable. If it is, then we have more elements to iterate over, so the function returns true. Otherwise, we have reached the end of the vector, so the function returns false.

Similarly, whenever the next() function is called, we simply need to return the element at the current index, and then increment the index variable.

Code:

class Vector2D { public: Vector2D(vector<vector<int>>& vec2d) { for (auto& row : vec2d) { for (auto x : row) { elems.push_back(x); } } index = 0; size = elems.size(); }

int next() {
    return elems[index++];
}

bool hasNext() {
    return index < size;
}

private: vector<int> elems; int index, size; };

Flatten 2d Vector Solution Code

1