251. Flatten 2D Vector

Approach 1: Store all elements in a new List

If we store all the elements in vec2d in a single 1D array and iterate over the array we can easily solve this problem.

class Vector2D(object):

    def __init__(self, vec2d):
        """
        Initialize your data structure here.
        :type vec2d: List[List[int]]
        """
        self.a = []
        for i in vec2d:
            self.a.extend(i)
        self.i = -1
        self.le = len(self.a)
            
    def next(self):
        """
        :rtype: int
        """
        self.i += 1
        # print(self.a, self.i)
        return self.a[self.i]

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.i < self.le-1

# Your Vector2D object will be instantiated and called as such:
# i, v = Vector2D(vec2d), []
# while i.hasNext(): v.append(i.next())

Time Complexity: O(N), where N = sum(length of all lists in vec2d)

Space Complexity: O(N), where N = sum(length of all lists in vec2d)

Last updated