use deque and defaultdict data structures