MediumNo. 0251LeetCode Premium

Flatten 2D Vector — LeetCode 251 Python Solution

Topics
Design, Array, Two Pointers, Iterator
Reading time
5 min

The problem

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Example

Input
["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
Output
[null, 1, 2, 3, true, true, 4, false]
Explanation
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);

Python solution

PythonSolution
class Vector2D:
    def __init__(self, vec: List[List[int]]):
        self.i = 0
        self.j = 0
        self.vec = vec

    def next(self) -> int:
        self.forward()
        ans = self.vec[self.i][self.j]
        self.j += 1
        return ans

    def hasNext(self) -> bool:
        self.forward()
        return self.i < len(self.vec)

    def forward(self):
        while self.i < len(self.vec) and self.j >= len(self.vec[self.i]):
            self.i += 1
            self.j = 0


# Your Vector2D object will be instantiated and called as such:
# obj = Vector2D(vec)
# param_1 = obj.next()
# param_2 = obj.hasNext()

Complexity

Time
O(n) (after optional sort O(n log n))
Space · auxiliary
O(1)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 251. Flatten 2D Vector is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0284Peeking IteratorMedium
0295Find Median from Data StreamHard
0307Range Sum Query - MutableMedium
0715Range ModuleHard
2276Count Integers in IntervalsHard
0900RLE IteratorMedium

Frequently asked questions

How hard is LeetCode 251. Flatten 2D Vector?

LeetCode 251. Flatten 2D Vector is rated Medium on LeetCode.

What is the time complexity of LeetCode 251. Flatten 2D Vector?

The Python solution on this page runs in O(n) (after optional sort O(n log n)).

What is the space complexity of LeetCode 251. Flatten 2D Vector?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 251. Flatten 2D Vector cover?

LeetCode 251. Flatten 2D Vector is tagged Design, Array, Two Pointers and Iterator on LeetCode.

Is LeetCode 251. Flatten 2D Vector a premium problem?

Yes. LeetCode 251. Flatten 2D Vector is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.