Skip to content

Dequeue

Deque Interface

Think of a train with doors on both ends πŸš† You can board or exit from the front or the back. That’s Deque in action.


🧠 What is Deque?

Deque belongs to the Java Collections Framework

Deque<Integer> deque = new ArrayDeque<>();

πŸ‘‰ It stands for Double-Ended Queue πŸ‘‰ Supports insertion and deletion from both ends


πŸ”‘ Key Characteristics

  • Add/remove from front and rear
  • Can act as:

    • Queue (FIFO)
    • Stack (LIFO)
    • No index-based access
    • Faster than legacy Stack and LinkedList (in many cases)

πŸ—οΈ Common Implementations

1. ArrayDeque (Most Preferred)

Image

Image

Image

Image

Image

Image

Image

Deque<Integer> deque = new ArrayDeque<>();
  • Uses resizable circular array
  • Very fast ⚑
  • Does not allow null

2. LinkedList

Image

Image

Image

Image

Image

Image

Deque<Integer> deque = new LinkedList<>();
  • Doubly linked list
  • Allows null
  • Slightly slower than ArrayDeque

βš™οΈ Important Methods

πŸ”Ή Insert

deque.addFirst(10);
deque.

addLast(20);

deque.

offerFirst(5);
deque.

offerLast(25);

πŸ”Ή Remove

deque.removeFirst();
deque.

removeLast();

deque.

pollFirst();
deque.

pollLast();

πŸ”Ή Peek

deque.peekFirst();
deque.

peekLast();

🧠 Example

Deque<Integer> dq = new ArrayDeque<>();

dq.

addFirst(10);  // [10]
dq.

addLast(20);   // [10, 20]
dq.

addFirst(5);   // [5, 10, 20]

System.out.

println(dq.removeLast()); // 20
        System.out.

println(dq);

Output:

20
[5, 10]

πŸ”„ Deque as Queue vs Stack

Behavior Method Used Example
Queue addLast + removeFirst FIFO
Stack addFirst + removeFirst LIFO

🎯 Interview Nuggets

  • Deque replaces Stack (preferred)
  • ArrayDeque is usually faster than LinkedList
  • No capacity restriction (dynamic)
  • Avoid using legacy Stack

🧠 Memory Trick

Deque = Queue + Stack (both ends open πŸ”)