Python solution with detailed explanation


  • 0
    G

    Solution

    Zigzag Iterator https://leetcode.com/problems/zigzag-iterator/

    Dictionary Based Solution

    • Keep a dictionary of list id to [list, next_index in list]
    class ZigzagIterator(object):
    
        def __init__(self, v1, v2):
            """
            Initialize your data structure here.
            :type v1: List[int]
            :type v2: List[int]
            """
            self.iter_map = {}
            if v1:
                self.iter_map[0] = [v1, 0]
            if v2:
                self.iter_map[1] = [v2, 0]
            self.next_id = 0
            
    
        def next(self):
            """
            :rtype: int
            """
            if self.next_id not in self.iter_map:
                self.next_id = self.next_id ^ 1
            lst, idx = self.iter_map[self.next_id][0], self.iter_map[self.next_id][1]
            result = lst[idx]
            if idx+1 == len(lst):
                del self.iter_map[self.next_id]
            else:
                self.iter_map[self.next_id][1] = idx+1
            self.next_id = self.next_id ^ 1
            return result
    
        def hasNext(self):
            """
            :rtype: bool
            """
            return len(self.iter_map) > 0
    

Log in to reply
 

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