Deque
Two ends of one structure
A Deque (double-ended queue) lets us add, inspect, and remove elements at both the front and the back. Unlike a regular queue, it supports operations on both ends. That means one deque can act as either a stack or a queue, and some algorithms genuinely need both ends at the same time.
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(20);
deque.addFirst(10);
deque.addLast(30);
int left = deque.removeFirst(); // 10
int right = deque.removeLast(); // 30
After these operations, only 20 remains in the structure.
With ArrayDeque, operations on both ends are amortized O(1).
Choose methods according to the role
The Deque interface contains many similar methods. If you use it as a stack,
it is convenient to stick to push, pop, and peek.
If you use it as a queue, work explicitly with addLast, removeFirst,
and peekFirst. This makes the direction of data movement visible in the code itself.
ArrayDeque does not allow
null.
This is useful to remember because some queue methods use null to indicate that no element is available.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in