Skip to lesson
MentorNxt home

Java Programming

Queues, Stacks & Priority Queues

Deque: both ends

A support desk serves tickets in order, but an urgent ticket must jump to the front, and the last one may be cancelled. One structure that works at both ends would help.

A queue with two ends

A deque (say deck) is a double-ended queue: a collection where you can add, remove and look at values at both the front and the back. In Java, ArrayDeque is the usual class that implements the Deque interface.

A deque lets you add, remove and look at values at both ends. The examples below use one ArrayDeque at both ends, then check a palindrome by comparing the two ends.

A deque of three orders with two ends. At the front offerFirst(x) adds and pollFirst() removes. At the back offerLast(x) adds and pollLast() removes. As a queue it adds at the back and removes at the front; as a stack it works only at the front.

Example 1 · Working at both ends

BothEndsDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class BothEndsDemo {    public static void main(String[] args) {        Deque<String> boarding = new ArrayDeque<>();        boarding.offerLast("Ravi");        boarding.offerLast("Sita");        boarding.offerFirst("Senior citizen");        boarding.offerLast("Tom");        System.out.println("Line: " + boarding);        System.out.println("Front: " + boarding.peekFirst() + ", back: " + boarding.peekLast());
        System.out.println("Boards: " + boarding.pollFirst());        System.out.println("Leaves the line: " + boarding.pollLast());        System.out.println("Line now: " + boarding);    }}
Output
Line: [Senior citizen, Ravi, Sita, Tom]
Front: Senior citizen, back: Tom
Boards: Senior citizen
Leaves the line: Tom
Line now: [Ravi, Sita]

What this code does

  • offerFirst lets the senior citizen join at the front; everyone else joins at the back with offerLast.
  • pollFirst serves the front, while pollLast lets the last person give up and leave. A plain queue cannot do that last step.

Example 2 · Palindrome check from both ends

PalindromeDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class PalindromeDemo {    static boolean isPalindrome(String text) {        Deque<Character> letters = new ArrayDeque<>();        for (char c : text.toLowerCase().toCharArray()) {            if (Character.isLetterOrDigit(c)) {                letters.offerLast(c);            }        }        while (letters.size() > 1) {            char front = letters.pollFirst();            char back = letters.pollLast();            if (front != back) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        String[] tests = { "Madam", "Never odd or even", "Java", "12321", "Was it a car or a cat I saw?" };        for (String t : tests) {            System.out.println(t + " -> " + isPalindrome(t));        }    }}
Output
Madam -> true
Never odd or even -> true
Java -> false
12321 -> true
Was it a car or a cat I saw? -> true

What this code does

  • Only letters and digits go into the deque, in lower case, so spaces and the ? are ignored.
  • Each pass takes one character from each end and compares them. The loop stops when 0 or 1 characters are left in the middle.

A normal queue lets people join only at the back. A deque also lets someone join at the front, and lets values leave from either end. Think of a local train coach with doors at both ends: people can get in and out at either door. Deque is an interface that extends Queue, and ArrayDeque is the class you create: Deque<String> d = new ArrayDeque<>();. All end operations are O(1). Like a queue, it has no index and does not allow null.

You already used it twice: as a queue (offer, poll) and as a stack (push, pop). Those methods are just names for particular ends.

The method families

Each end has the same three jobs as a queue, with the end in the name. The code below adds at both ends of one ArrayDeque, looks at both ends and removes from both.

DequeEnds.javaJava
import java.util.*;
public class DequeEnds {    public static void main(String[] args) {        Deque<String> line = new ArrayDeque<>();        line.offerLast("Asha");        line.offerLast("Ravi");        line.offerFirst("Meena");        System.out.println(line);        System.out.println(line.peekFirst() + " " + line.peekLast());        System.out.println(line.pollFirst() + " " + line.pollLast());        System.out.println(line.pollLast() + " " + line.pollLast());    }}
Output
[Meena, Asha, Ravi]
Meena Ravi
Meena Ravi
Asha null

The offer/poll/peek forms return false or null when they cannot work; the add/remove/get forms throw an exception. The four families:

  • Front: offerFirst(x), pollFirst(), peekFirst() (throwing forms: addFirst, removeFirst, getFirst).
  • Back: offerLast(x), pollLast(), peekLast() (throwing forms: addLast, removeLast, getLast).
  • As a queue: offer = offerLast, poll = pollFirst, peek = peekFirst.
  • As a stack: push = addFirst, pop = removeFirst, and peek is again peekFirst.
descendingIterator() walks the deque from the back to the front, without removing anything.

The mixing trap

push adds at the front and offer adds at the back. Mixing them on one deque gives orders that surprise everyone. The example below shows it.

Example 3 · Trap: mixing push and offer

MixingTrapDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class MixingTrapDemo {    public static void main(String[] args) {        Deque<Integer> d = new ArrayDeque<>();        d.offer(1);        d.push(2);        d.offer(3);        d.push(4);        System.out.println("Deque: " + d);        System.out.println("poll() gives " + d.poll() + ", pop() gives " + d.pop());        System.out.println("Left: " + d);    }}
Output
Deque: [4, 2, 1, 3]
poll() gives 4, pop() gives 2
Left: [1, 3]

What this code does

  • push adds at the front and offer at the back, so 1 and 3 end up behind 2 and 4. Few people would guess [4, 2, 1, 3].
  • poll and pop both take from the front, so neither returns 1, the first value added. Use one role per deque, or the explicit First/Last methods.

The rule is simple. Decide what a deque is for. If it is a stack, use only push, pop, peek. If it is a queue, use only offer, poll, peek. If you really need both ends, use the explicit First/Last names, so every line says which end it touches.

Predict the output

Predict the deque

push adds at the front and offer adds at the back. What does each snippet print?

Round 1 of 2

What does this print?

Deque<String> d = new ArrayDeque<>();
d.offer("A");
d.push("B");
d.offer("C");
System.out.println(d);

The sliding window idea

A window is a fixed number of neighbouring values, like "the last 3 overs". The examples below keep a bounded history and then find the biggest value in every window.

Example 4 · Keep only the last 3 transactions

RecentPaymentsDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;import java.util.Iterator;
public class RecentPaymentsDemo {    public static void main(String[] args) {        int limit = 3;        Deque<String> recent = new ArrayDeque<>();        String[] payments = { "Rs. 120 Courier", "Rs. 40 Metro", "Rs. 899 Amazon", "Rs. 15 Stationery", "Rs. 250 Recharge" };
        for (String p : payments) {            recent.offerLast(p);            if (recent.size() > limit) {                recent.pollFirst();            }        }        System.out.println("Oldest first: " + recent);
        System.out.println("Newest first:");        Iterator<String> it = recent.descendingIterator();        while (it.hasNext()) {            System.out.println("  " + it.next());        }    }}
Output
Oldest first: [Rs. 899 Amazon, Rs. 15 Stationery, Rs. 250 Recharge]
Newest first:
  Rs. 250 Recharge
  Rs. 15 Stationery
  Rs. 899 Amazon

What this code does

  • New payments enter at the back. When there are more than 3, the oldest leaves from the front, so the deque never grows past 3.
  • descendingIterator() walks from back to front, which here means newest first, as a payments app would show it.

Example 5 · Sliding window maximum: best 3 overs

BestOversDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class BestOversDemo {    public static void main(String[] args) {        int[] runs = { 4, 9, 2, 6, 11, 3, 5, 8 };        int k = 3;
        Deque<Integer> window = new ArrayDeque<>();        for (int i = 0; i < runs.length; i++) {            if (!window.isEmpty() && window.peekFirst() <= i - k) {                window.pollFirst();            }            while (!window.isEmpty() && runs[window.peekLast()] <= runs[i]) {                window.pollLast();            }            window.offerLast(i);
            if (i >= k - 1) {                int start = i - k + 2;                System.out.println("Overs " + start + "-" + (i + 1) + ": best over " + runs[window.peekFirst()] + " runs");            }        }    }}
Output
Overs 1-3: best over 9 runs
Overs 2-4: best over 9 runs
Overs 3-5: best over 11 runs
Overs 4-6: best over 11 runs
Overs 5-7: best over 11 runs
Overs 6-8: best over 8 runs

What this code does

  • The deque holds over positions, with their runs in decreasing order. A new over removes smaller overs from the back, because they can never be the best again while it is in the window.
  • If the front position has slid out of the window (<= i - k), it is dropped. The front is then always the best over of the current 3.

As new data arrives, the window slides: the new value enters at the back and the oldest leaves from the front. A deque does both in O(1). The simplest use is a bounded history: offerLast(x), then pollFirst() if the size is over the limit.

A famous harder use is the sliding window maximum: the biggest value in every window. The deque stores positions whose values are in decreasing order. Before adding a new position, pop smaller values from the back, since they can never be the maximum again. Drop the front if it has slid out of the window. The front is then always the maximum. Each position enters and leaves once, so the whole job is O(n).

Next step

Check your understanding

12 quick questions