Skip to lesson

A deque (double-ended queue) supports insertion and deletion at both the front and the back in O(1) time. It unifies stacks and queues into one versatile data structure.

Dual-ended operations with ArrayDeque

A deque is a double-ended queue that supports insertion and removal at both the front and the back.

A deque adds and removes items at both ends in O(1) time. Java's ArrayDeque offers offerFirst, offerLast, pollFirst and pollLast.

  1. Call offerFirst(10) to insert 10 at the front.
  2. Call offerLast(20) to insert 20 at the back.
  3. Call pollFirst() to remove 10 from the front.
  4. Call pollLast() to remove 20 from the back.

Example 1 · Dual-Ended Operations with ArrayDeque

DequeOperationsDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class DequeOperationsDemo {    public static void main(String[] args) {        Deque<Integer> deque = new ArrayDeque<>();        deque.offerFirst(10);        deque.offerLast(20);        deque.offerFirst(5);
        System.out.println("First: " + deque.peekFirst());        System.out.println("Last: " + deque.peekLast());        System.out.println("Polled first: " + deque.pollFirst());        System.out.println("Polled last: " + deque.pollLast());    }}
Output
First: 5
Last: 20
Polled first: 5
Polled last: 20

What this code does

  • 5 is placed at the front, 20 at the back.
  • pollFirst retrieves 5 and pollLast retrieves 20.
  • All operations take O(1) time.

The four core operations:

  • addFirst(e) / offerFirst(e): inserts at the front.
  • addLast(e) / offerLast(e): inserts at the rear.
  • pollFirst(): removes and returns front element.
  • pollLast(): removes and returns rear element.

A deque is the right tool when a problem touches both ends, such as the sliding window maximum in the last section. Scanning all k values of every window takes O(n * k) time, while a monotonic decreasing deque that keeps only candidates for the maximum finishes in O(n). Trace on [1, 3, -1, -3, 5] with k = 3 (the deque holds indexes):

  • Index 0 (1): deque [0].
  • Index 1 (3): 3 > 1, so drop index 0; deque [1].
  • Index 2 (-1): -1 < 3, so add 2; deque [1, 2]. The first window maximum is nums[1] = 3.
  • Index 3 (-3): add 3; deque [1, 2, 3]. The window maximum is nums[1] = 3.
  • Index 4 (5): 5 beats everything, so drop all; deque [4]. The window maximum is nums[4] = 5.

When deque.peekFirst() <= i - k, the front index has left the window and must be removed with pollFirst().

Palindrome verification and middle manipulations

A deque provides a clean, elegant way to check if a word is a palindrome.

Add all characters into a deque. In a loop, compare pollFirst() with pollLast().

Example 2 · Palindrome Check Using a Deque

DequePalindromeDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class DequePalindromeDemo {    public static boolean isPalindrome(String s) {        Deque<Character> deque = new ArrayDeque<>();        for (char c : s.toLowerCase().toCharArray()) {            if (Character.isLetterOrDigit(c)) deque.offerLast(c);        }
        while (deque.size() > 1) {            if (deque.pollFirst() != deque.pollLast()) return false;        }        return true;    }
    public static void main(String[] args) {        System.out.println("radar: " + isPalindrome("radar"));        System.out.println("mentor: " + isPalindrome("mentor"));    }}
Output
radar: true
mentor: false

What this code does

  • Letters are loaded into the deque.
  • pollFirst() and pollLast() match symmetric characters inwards.
  • Terminates cleanly in O(n) time.

If front and back characters match until 0 or 1 elements remain, the word is a palindrome. This avoids pointer index calculations.

Remember:

  • Front and back comparison: pollFirst() matches pollLast().
  • Termination: stop when deque size is 0 (even length) or 1 (odd length).
  • Mismatch: any inequality immediately proves the string is not a palindrome.

Monotonic deque: sliding window maximum revisited

Finding the maximum value in every sliding window of size k takes O(n * k) with brute force. A monotonic deque solves it in O(n) time.

Example 3 · Brute force: rescan every window (O(n * k) time, O(1) extra space)

WindowMaxBruteDemo.javaJava
import java.util.Arrays;
public class WindowMaxBruteDemo {    static int[] maxSlidingWindow(int[] nums, int k) {        int[] res = new int[nums.length - k + 1];        for (int start = 0; start < res.length; start++) {            int max = nums[start];            for (int j = start + 1; j < start + k; j++) {                max = Math.max(max, nums[j]);            }            res[start] = max;        }        return res;    }
    public static void main(String[] args) {        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};        System.out.println(Arrays.toString(maxSlidingWindow(nums, 3)));    }}
Output
[3, 3, 5, 5, 6, 7]

What this code does

  • Each of the n - k + 1 windows is scanned from scratch, and each scan reads k values.
  • For k = 10,000 on 1,000,000 values that is about 10 billion reads.
  • Neighbouring windows share k - 1 values, which the monotonic deque in the next example reuses.

Example 4 · Optimal: sliding window maximum with a monotonic deque (O(n) time, O(k) space)

SlidingWindowMaxDemo.javaJava
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;
public class SlidingWindowMaxDemo {    public static int[] maxSlidingWindow(int[] nums, int k) {        int n = nums.length;        int[] res = new int[n - k + 1];        Deque<Integer> dq = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {            if (!dq.isEmpty() && dq.peekFirst() < i - k + 1) {                dq.pollFirst();            }            while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) {                dq.pollLast();            }            dq.offerLast(i);            if (i >= k - 1) {                res[i - k + 1] = nums[dq.peekFirst()];            }        }        return res;    }
    public static void main(String[] args) {        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};        System.out.println(Arrays.toString(maxSlidingWindow(nums, 3)));    }}
Output
[3, 3, 5, 5, 6, 7]

What this code does

  • The monotonic deque keeps indices in decreasing order of values.
  • Front element dq.peekFirst() always holds the window maximum.
  • Runs in strict O(n) time across all windows.

The deque stores indices in decreasing order of their corresponding values. peekFirst() always points to the maximum element in the current window. Remove expired indices from the front and smaller values from the back before adding i.

The rules:

  • Front cleanup: remove indices outside the current window i - k + 1.
  • Back cleanup: remove indices whose values are <= incoming value.
  • Window maximum: nums[deque.peekFirst()] is the maximum for the window ending at i.
Every element is added and removed from the monotonic deque at most once, guaranteeing linear O(n) execution time.

Next step

Check your understanding

10 quick questions