Deque in Java

A thorough guide to the Deque interface in Java: double-ended queue operations, ArrayDeque internals, stack and queue usage, and interview questions.

Deque<E> (pronounced "deck") stands for Double-Ended Queue. It extends Queue<E> and allows elements to be inserted and removed at both the head and the tail. This makes a Deque useful as a FIFO queue, a LIFO stack, a sliding-window buffer, or an undo/redo stack — all with O(1) operations at both ends. The primary implementation is ArrayDeque, and the Java documentation recommends it over the legacy Stack class for LIFO stacks and over LinkedList for FIFO queues.

The Deque Interface

Deque<E> defines operations for both ends. Most operations come in three forms: one that throws an exception on failure, one that returns a special value, and one inherited push/pop stack alias.

Operation Head (throws) Head (returns special) Tail (throws) Tail (returns special)
Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
Remove removeFirst() pollFirst() removeLast() pollLast()
Examine getFirst() peekFirst() getLast() peekLast()

Stack Aliases on Deque

When using Deque as a LIFO stack, use these convenience methods (all operate on the head):

Method Equivalent Deque call Description
push(e) addFirst(e) Pushes to the head (top of stack)
pop() removeFirst() Removes from the head (top of stack)
peek() peekFirst() Examines the head without removing

Queue Aliases on Deque

When using Deque as a FIFO queue, use the inherited Queue methods:

Method Equivalent Deque call Description
offer(e) offerLast(e) Enqueues at the tail
poll() pollFirst() Dequeues from the head
peek() peekFirst() Examines the head without removing

ArrayDeque Internals

ArrayDeque stores elements in a circular resizable array. Two integer pointers, head and tail, track where the next element should be read and written. When the array fills up, a new array roughly twice as large is allocated and elements are copied. Because elements are stored contiguously (modulo wrap-around), CPU cache performance is excellent. ArrayDeque does not allow null elements.

Time Complexities

Operation Complexity Notes
addFirst / addLast Amortized O(1) O(n) on rare resize
pollFirst / pollLast O(1) Move head or tail pointer
peekFirst / peekLast O(1) No pointer movement
contains(o) O(n) Linear scan
size() O(1) Field read

Example 1: Deque as a Stack and a Queue

import java.util.ArrayDeque;
import java.util.Deque;

public class DequeAsBoth {
    public static void main(String[] args) {
        // Used as a LIFO Stack
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        System.out.println("Stack top: " + stack.peek()); // 30
        System.out.println("Stack pop: " + stack.pop());  // 30 (LIFO)
        System.out.println("Stack pop: " + stack.pop());  // 20

        // Used as a FIFO Queue
        Deque<String> queue = new ArrayDeque<>();
        queue.offerLast("first");
        queue.offerLast("second");
        queue.offerLast("third");
        System.out.println("Queue head: " + queue.peekFirst()); // first
        System.out.println("Queue poll: " + queue.pollFirst()); // first (FIFO)
        System.out.println("Queue poll: " + queue.pollFirst()); // second
    }
}

Example 2: Sliding Window Maximum with a Deque

A monotonic deque is a classic algorithmic pattern where the deque maintains elements in decreasing (or increasing) order, enabling O(1) maximum/minimum queries over a sliding window.

import java.util.ArrayDeque;
import java.util.Deque;

public class SlidingWindowMax {
    // Returns the maximum value in each window of size k
    public static int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        int[] result = new int[n - k + 1];
        Deque<Integer> deque = new ArrayDeque<>(); // stores indices

        for (int i = 0; i < n; i++) {
            // Remove indices outside the current window
            while (!deque.isEmpty() && deque.peekFirst() < i - k + 1) {
                deque.pollFirst();
            }
            // Remove indices of elements smaller than current (maintain decreasing order)
            while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
                deque.pollLast();
            }
            deque.offerLast(i);
            if (i >= k - 1) {
                result[i - k + 1] = nums[deque.peekFirst()];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] result = maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 3);
        for (int v : result) System.out.print(v + " "); // 3 3 5 5 6 7
    }
}

ArrayDeque vs. LinkedList

Feature ArrayDeque LinkedList
Internal structure Circular array Doubly-linked list
Memory per element ~4–8 bytes ~48 bytes (node object)
Cache performance Excellent Poor (pointer chasing)
addFirst/addLast Amortized O(1) O(1)
pollFirst/pollLast O(1) O(1)
null elements Not allowed Allowed
Implements List No Yes
Recommended for stack/queue Yes No

Common Mistakes

  • Confusing which end is the "stack top". When using Deque as a stack, push and pop operate on the head (first element). peekFirst() is the top. Calling peekLast() or pollLast() retrieves the bottom of the stack.
  • Passing null to ArrayDeque. ArrayDeque throws NullPointerException for null elements. The poll and peek methods return null to signal an empty deque, so allowing nulls would create ambiguity.
  • Using ArrayDeque where LinkedList is needed for List operations. ArrayDeque does not implement List, so it has no get(i), set(i, e), or subList. If you need both deque and list behaviour, use LinkedList — but this is rarely the right design.
  • Iterating a Deque with index-based loops. ArrayDeque has no get(i) method. Use the for-each loop or explicit iterator. The for-each iterates head to tail.
  • Assuming Deque iterates in LIFO order when used as a stack. The iterator of ArrayDeque iterates head-to-tail (i.e., top-to-bottom when used as a stack). If you need bottom-to-top, use descendingIterator().

Best Practices

  • Use Deque<E> deque = new ArrayDeque<>() as your default stack and queue implementation.
  • Explicitly name the variable "stack" or "queue" to signal intended usage, even though the declared type is Deque.
  • For algorithm problems (DFS, BFS, sliding window), always reach for ArrayDeque — it has no synchronisation overhead and excellent performance.
  • For concurrent deque access, use ConcurrentLinkedDeque or LinkedBlockingDeque.
  • Prefer pollFirst/pollLast/peekFirst/peekLast over remove/get to avoid exceptions on empty deques.

Interview Questions

1. What is a Deque in Java?

Deque<E> is a double-ended queue that supports O(1) insertion and removal at both the head and the tail. It extends Queue<E> and can serve as a FIFO queue, a LIFO stack, or a structure that needs efficient access from both ends. The primary implementation is ArrayDeque.

2. How does ArrayDeque work internally?

ArrayDeque uses a circular resizable array. Two integer indices, head and tail, point to the next read and write positions. When the array is full, it doubles in size and elements are re-laid out. Because elements are contiguous in memory, cache performance is far better than LinkedList's pointer-chasing structure.

3. Why does the Java documentation recommend ArrayDeque over Stack?

java.util.Stack extends Vector and is synchronised, which adds lock overhead even in single-threaded code. It also inherits all of Vector's index-based methods (get, set, etc.), which can violate the LIFO contract. ArrayDeque is unsynchronised, faster, and exposes only the Deque API, making the LIFO contract clear.

4. What is the difference between push/pop and offerFirst/pollFirst on a Deque?

push(e) is exactly equivalent to addFirst(e) and throws IllegalStateException if the deque is full (not relevant for ArrayDeque). pop() is exactly equivalent to removeFirst() and throws NoSuchElementException on an empty deque. offerFirst and pollFirst are the null/false-returning variants that do not throw.

5. What is a monotonic deque and why is it useful?

A monotonic deque maintains elements in a monotonically increasing or decreasing order by discarding elements from the tail when they violate the invariant. This enables O(1) access to the running minimum or maximum. It is the key data structure for solving sliding-window maximum/minimum problems in O(n) time instead of O(n * k).

6. Is ArrayDeque thread-safe?

No. ArrayDeque is not synchronised. For concurrent access, use ConcurrentLinkedDeque (lock-free, unbounded) or LinkedBlockingDeque (optional capacity, blocking operations) from java.util.concurrent.

7. What is the difference between peekFirst and peekLast?

peekFirst() returns (without removing) the element at the head of the deque — the next element to be polled in FIFO order, or the top of the stack in LIFO order. peekLast() returns the element at the tail — the most recently added in FIFO mode, or the bottom of the stack. Both return null if the deque is empty.

Summary

  • Deque<E> is a double-ended queue supporting O(1) add/remove at both ends; it extends Queue<E>.
  • ArrayDeque is the preferred implementation: circular array, no null support, no synchronisation, excellent cache performance.
  • push/pop operate on the head (LIFO stack); offer/poll insert at tail and remove from head (FIFO queue).
  • ArrayDeque is preferred over both java.util.Stack and LinkedList for stack and queue use cases.
  • Monotonic deques are a powerful algorithmic pattern for O(n) sliding-window extremes.

Continue Learning

Previous: Queue | Next: PriorityQueue

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.