use deque instead of stack, conciser code