improve performance by using collections.deque where appropriate