Flatten 2D Vector — LeetCode 251 Python Solution

MediumLeetCode PremiumDesignArrayTwo PointersIterator
Problem
#251
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

Python
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

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

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

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.

Get Stealth Interview