Simple Python solution using deque


  • 0
    K

    Since list takes O(n) time for poping the first element, we can use deque which can append and popleft in O(1) time complexity. Also, this can be extended to k lists without affecting the order of function calls.

    def __init__(self, v1, v2):
        self.q = collections.deque([(v, 0, len(v)) for v in [v1, v2] if v])
    
    def next(self):
        v, p, maxl = self.q.popleft()
        if p+1 < maxl:
            self.q.append((v, p+1, maxl))
        return v[p]
    
    def hasNext(self):
        return True if self.q else False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.