Solution with custom deque.