# 251 Flatten 2D Vector

Implement an iterator to flatten a 2d vector.

For example,\
Given 2d vector =

```
[
  [1,2],
  [3],
  [4,5,6]
]
```

By callingnextrepeatedly untilhasNextreturns false, the order of elements returned bynextshould be:`[1,2,3,4,5,6]`.

**Follow up:**\
As an added challenge, try to code it using only [iterators in C++](http://www.cplusplus.com/reference/iterator/iterator/) or [iterators in Java](http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html).

**The Idea:** Maintain a row and column pointer, and update these for each `next()` call. The row will increments as the column will reset to 0, when the column index is going to exceed it's current row vector. One challenge was dealing with empty vectors `{}`. These need to be ignored and iterated over every time we enter the start of a new row.

**Complexity:** O(n) time where n is the total number of elements in the vector.

```cpp
class Vector2D {
public:
    Vector2D(vector<vector<int>>& vec2d) {
        v = &vec2d;
        r = c = 0;
        _skip_empty_vectors();
    }

    int next() {
        // current r and c should always be valid
        int cur_row = r, cur_col = c;

        // update for next call
        if (cur_col + 1 >= v->at(cur_row).size()) {
            c = 0;
            r++;
            _skip_empty_vectors();
        }
        else c++;

        return v->at(cur_row).at(cur_col);
    }

    bool hasNext() {
        return r < v->size();
    }

private:
    int r, c;
    vector<vector<int>> *v;

    void _skip_empty_vectors() {
        while (hasNext() && v->at(r).empty()) {
            r++;
        }
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/251-flatten-2d-vector.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
