Java Collections
Queue / Deque
Complete lesson for Queue / Deque using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Queue / Deque
Section: Java Collections. A queue is a First-In, First-Out (FIFO) collection: the first item added is the first one served. Learn offer, poll, peek, the two method styles, ArrayDeque, Deque, PriorityQueue, circular queues, heaps, BFS, BlockingQueue, and sliding windows — all with real-life examples.
What is a queue?
- A queue is a linear collection where items are added at one end (the rear) and removed from the other end (the front).
- It follows FIFO — First In, First Out. The item that waited longest is served first.
- Core operations:
offer(join at the rear),poll(leave from the front), andpeek(see who is at the front). - In Java,
Queueis an interface. UseQueue<E> q = new ArrayDeque<>();for a general-purpose queue. - Real life: a railway ticket counter line. The person who came first gets the ticket first, and newcomers join at the back.
import java.util.ArrayDeque;
import java.util.Queue;
public class TicketCounter {
public static void main(String[] args) {
Queue<String> line = new ArrayDeque<>();
line.offer("Asha"); // first to arrive
line.offer("Ravi");
line.offer("Kiran"); // last to arrive
System.out.println("Next to be served: " + line.peek()); // Asha
System.out.println("Served: " + line.poll()); // Asha
System.out.println("Served: " + line.poll()); // Ravi
line.offer("Meena"); // joins at the rear
System.out.println("Line now: " + line); // [Kiran, Meena]
}
} Queue operations
| Operation | What it does | Throws an exception | Returns a special value |
|---|---|---|---|
| Insert | Adds an item at the rear | add(e) — IllegalStateException if a bounded queue is full | offer(e) — returns false if full |
| Remove | Removes and returns the front item | remove() — NoSuchElementException if empty | poll() — returns null if empty |
| Examine | Returns the front item without removing it | element() — NoSuchElementException if empty | peek() — returns null if empty |
| Check empty | True if there are no items | — | isEmpty() |
| Count | Number of items | — | size() |
import java.util.ArrayDeque;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue<Integer> queue = new ArrayDeque<>();
System.out.println("1. empty? " + queue.isEmpty()); // true
queue.offer(10);
System.out.println("2. offer 10: " + queue); // [10]
queue.offer(20);
System.out.println("3. offer 20: " + queue); // [10, 20]
queue.offer(30);
System.out.println("4. offer 30: " + queue); // [10, 20, 30] (front first)
System.out.println("5. peek: " + queue.peek() + " -> " + queue); // 10 -> [10, 20, 30]
System.out.println("6. poll: " + queue.poll() + " -> " + queue); // 10 -> [20, 30]
}
} Java queue operations — offer, peek, and poll step by step
A queue has two ends. offer adds an item at the rear, peek looks at the
item at the front without removing it, and poll removes the front item. Like a ticket
counter line, whoever joined first is served first — FIFO: First In, First Out.
- offer(e): adds
eat the rear — returnsfalseonly if a bounded queue is full. - peek(): returns the front item (10) and leaves the queue unchanged.
- poll(): removes and returns the front item (10) — 20 becomes the new front.
- Empty queue:
peek()andpoll()returnnullinstead of throwing.
Real-life examples of queue
| Real-life scenario | offer means | poll means |
|---|---|---|
| Railway ticket counter | A passenger joins the line | The front passenger gets a ticket |
| Bank token system | A token is issued | The next token is called to the counter |
| Office printer | A document is sent to print | The printer prints the oldest job |
| Call centre | A caller is put on hold | The next free agent takes the oldest call |
| Toll plaza lane | A car arrives at the booth | The front car pays and leaves |
| Food delivery app | A customer places an order | The kitchen prepares the oldest order |
| Chat messages | A message is sent | Messages are delivered in the order sent |
| Music playlist "play next" | A song is added to the queue | The next song starts playing |
| CPU scheduling | A process becomes ready | The scheduler runs the next process |
| Keyboard buffer | A key is pressed | The program reads keys in typing order |
Two styles of queue methods
- Every queue action has two versions: one throws an exception on failure, the other returns a special value (
falseornull). - Use
offer,poll, andpeekin normal application code; useadd,remove, andelementwhen failure means a bug. - For unbounded queues like
ArrayDeque,addandofferboth always succeed. The difference shows on bounded queues. - Real life: a parking lot with only 2 slots. A polite guard says "full" (
offerreturns false); a strict guard raises an alarm (addthrows).
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class ParkingQueue {
public static void main(String[] args) {
Queue<String> parking = new ArrayBlockingQueue<>(2); // only 2 slots
System.out.println(parking.offer("Car A")); // true
System.out.println(parking.offer("Car B")); // true
System.out.println(parking.offer("Car C")); // false: full, no exception
try {
parking.add("Car C");
} catch (IllegalStateException e) {
System.out.println("add on a full queue: IllegalStateException");
}
parking.clear();
System.out.println(parking.poll()); // null: empty, no exception
System.out.println(parking.peek()); // null
try {
parking.remove();
} catch (NoSuchElementException e) {
System.out.println("remove on an empty queue: NoSuchElementException");
}
try {
parking.element();
} catch (NoSuchElementException e) {
System.out.println("element on an empty queue: NoSuchElementException");
}
}
} Queue implementations in Java
| Class | Order | Bounded? | Thread-safe? | Real-life use |
|---|---|---|---|---|
ArrayDeque | FIFO | No (grows) | No | Ticket line, BFS, task list |
LinkedList | FIFO | No | No | Queue that must allow null |
PriorityQueue | By priority (smallest first) | No | No | Hospital emergency room |
ArrayBlockingQueue | FIFO | Yes (fixed) | Yes, blocking | Pickup shelf with limited space |
LinkedBlockingQueue | FIFO | Optional | Yes, blocking | Thread pool work queue |
ConcurrentLinkedQueue | FIFO | No | Yes, lock-free | High-traffic event logging |
PriorityBlockingQueue | By priority | No | Yes, blocking | Shared priority job scheduler |
DelayQueue | By expiry time | No | Yes, blocking | Reminders and session timeouts |
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class CreateQueues {
public static void main(String[] args) {
Queue<String> a = new ArrayDeque<>(); // general FIFO (recommended)
Queue<String> b = new LinkedList<>(); // FIFO, allows null
Queue<Integer> c = new PriorityQueue<>(); // smallest first
Queue<Integer> d = new PriorityQueue<>(Comparator.reverseOrder()); // largest first
BlockingQueue<String> e = new ArrayBlockingQueue<>(100); // bounded, thread-safe
Queue<String> f = new ConcurrentLinkedQueue<>(); // lock-free, thread-safe
for (int x : new int[] { 5, 1, 3 }) {
c.offer(x);
d.offer(x);
}
System.out.println("Min-heap front: " + c.peek() + ", max-heap front: " + d.peek()); // 1, 5
System.out.println(a.isEmpty() + " " + b.isEmpty() + " " + e.remainingCapacity() + " " + f.size());
// true true 100 0
}
} Using ArrayDeque as a queue
ArrayDequeis the fastest general-purpose queue: a resizable circular array with O(1)offerandpoll.- Declare it as
Queue<E>so only queue methods are visible.offeradds at the tail andpollremoves from the head. ArrayDequedoes not allownull, becausepollandpeekusenullto mean "empty".- Real life: a bank token machine issuing token numbers and the display calling them in order.
import java.util.ArrayDeque;
import java.util.Queue;
public class BankTokens {
public static void main(String[] args) {
Queue<Integer> tokens = new ArrayDeque<>();
int nextToken = 101;
for (int i = 0; i < 4; i++) {
tokens.offer(nextToken);
System.out.println("Token issued: " + nextToken);
nextToken++;
}
// Token issued: 101, 102, 103, 104
while (!tokens.isEmpty()) {
int t = tokens.poll();
System.out.println("Token " + t + " to counter 1. Still waiting: " + tokens.size());
}
// Token 101 to counter 1. Still waiting: 3
// Token 102 to counter 1. Still waiting: 2
// Token 103 to counter 1. Still waiting: 1
// Token 104 to counter 1. Still waiting: 0
}
} Iterating a queue
- Looping with for-each just looks at the line; polling actually serves people and empties it.
- Real life: a restaurant kitchen reading the order slips on the rail, cancelling one, then cooking the rest in order.
| Way | Order | Removes items? |
|---|---|---|
for-each / forEach | Front to rear | No |
while (!q.isEmpty()) q.poll() | Front to rear | Yes (drains the queue) |
removeIf(condition) | — | Removes matching items only |
Iterator with remove() | Front to rear | Only the ones you remove |
for-each on a PriorityQueue | Heap order (not sorted!) | No |
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
public class KitchenOrders {
public static void main(String[] args) {
Queue<String> orders = new ArrayDeque<>(List.of("Dosa", "Idli", "Vada", "Poori"));
for (String o : orders) System.out.print(o + " "); // Dosa Idli Vada Poori
System.out.println("| still " + orders.size()); // still 4
orders.removeIf(o -> o.equals("Vada")); // a customer cancelled vada
System.out.println(orders); // [Dosa, Idli, Poori]
while (!orders.isEmpty()) {
System.out.println("Cooking " + orders.poll()); // Dosa, Idli, Poori
}
System.out.println("Orders left: " + orders.size()); // 0
}
} Deque: double-ended queue
Deque(pronounced "deck") lets you add and remove at both ends. It can behave as a queue (FIFO), a stack (LIFO), or both.ArrayDequeandLinkedListimplementDeque. Each operation again comes in a throwing and a special-value version.- Real life: a railway reservation line where a senior citizen is allowed to join at the front, and a tired person may leave from the back.
| Action | Front — throws | Front — special value | Rear — throws | Rear — special value |
|---|---|---|---|---|
| Insert | addFirst(e) | offerFirst(e) | addLast(e) | offerLast(e) |
| Remove | removeFirst() | pollFirst() | removeLast() | pollLast() |
| Examine | getFirst() | peekFirst() | getLast() | peekLast() |
import java.util.ArrayDeque;
import java.util.Deque;
public class ReservationLine {
public static void main(String[] args) {
Deque<String> line = new ArrayDeque<>();
line.offerLast("Ravi");
line.offerLast("Asha");
line.offerLast("Kiran");
line.offerFirst("Senior: Mr Rao"); // allowed to join at the front
System.out.println(line); // [Senior: Mr Rao, Ravi, Asha, Kiran]
System.out.println("Served: " + line.pollFirst()); // Senior: Mr Rao
System.out.println("Left the line: " + line.pollLast()); // Kiran (tired of waiting)
System.out.println("Front: " + line.peekFirst() + ", Rear: " + line.peekLast()); // Front: Ravi, Rear: Asha
}
} PriorityQueue: serve by priority
PriorityQueuedoes not serve in arrival order. It always gives the highest-priority item first — by default the smallest (min-heap).- Give it a
Comparatorto define priority for your own objects.offerandpollare O(log n);peekis O(1). - Printing or iterating a
PriorityQueueis NOT sorted — only repeatedpollgives sorted order. It does not allownull. - Real life: a hospital emergency room treats the most critical patient first, not the one who arrived first.
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class EmergencyRoom {
record Patient(String name, int severity) { } // 1 = most critical
public static void main(String[] args) {
PriorityQueue<Patient> er = new PriorityQueue<>(Comparator.comparingInt(Patient::severity));
er.offer(new Patient("Fever", 4));
er.offer(new Patient("Heart attack", 1));
er.offer(new Patient("Broken arm", 3));
er.offer(new Patient("Accident", 2));
System.out.println("Next: " + er.peek().name()); // Heart attack
while (!er.isEmpty()) {
Patient p = er.poll();
System.out.println("Treating " + p.name() + " (severity " + p.severity() + ")");
}
// Heart attack (1), Accident (2), Broken arm (3), Fever (4)
PriorityQueue<Integer> nums = new PriorityQueue<>(List.of(5, 1, 4, 2, 3));
System.out.println(nums); // [1, 2, 4, 5, 3] heap order, not sorted
}
} PriorityQueue with a custom Comparator
- Combine rules with
Comparator.comparing(...).thenComparing(...)to decide priority on several fields. - For a max-heap (largest first) use
new PriorityQueue<>(Comparator.reverseOrder()). - Real life: airline boarding — business class first, and within each class, passengers in the back rows board first.
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class AirlineBoarding {
record Passenger(String name, String travelClass, int row) { }
public static void main(String[] args) {
Comparator<Passenger> order = Comparator
.comparingInt((Passenger p) -> p.travelClass().equals("Business") ? 0 : 1) // business first
.thenComparing(Passenger::row, Comparator.reverseOrder()); // back rows first
PriorityQueue<Passenger> gate = new PriorityQueue<>(order);
gate.offer(new Passenger("Anil", "Economy", 12));
gate.offer(new Passenger("Bina", "Business", 2));
gate.offer(new Passenger("Chetan", "Economy", 30));
gate.offer(new Passenger("Divya", "Business", 1));
gate.offer(new Passenger("Esha", "Economy", 21));
while (!gate.isEmpty()) System.out.print(gate.poll().name() + " ");
System.out.println(); // Bina Divya Chetan Esha Anil
PriorityQueue<Integer> bids = new PriorityQueue<>(Comparator.reverseOrder());
bids.addAll(List.of(40, 95, 70));
System.out.println("Highest bid: " + bids.peek()); // 95
}
} Round robin with a queue
- Poll an item from the front, give it a turn, then offer it back at the rear. Everyone gets a fair, repeating turn.
- Operating systems use this round-robin idea to share the CPU between processes.
- Real life: players taking turns in a Ludo game — after your turn, you go to the end of the line.
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
public class LudoTurns {
public static void main(String[] args) {
Queue<String> players = new ArrayDeque<>(List.of("Red", "Green", "Yellow", "Blue"));
for (int turn = 1; turn <= 6; turn++) {
String p = players.poll(); // whose turn is it?
System.out.println("Turn " + turn + ": " + p);
players.offer(p); // back to the end of the line
}
// Turn 1: Red, Turn 2: Green, Turn 3: Yellow, Turn 4: Blue, Turn 5: Red, Turn 6: Green
}
} Differences between Queue, Deque, and PriorityQueue
| Feature | Queue | Deque | PriorityQueue |
|---|---|---|---|
| Type | Interface | Interface (extends Queue) | Class (implements Queue) |
| Order | FIFO | FIFO, LIFO, or both | By priority (Comparator) |
| Insert at | Rear only | Front or rear | Its heap position |
| Remove from | Front only | Front or rear | Highest priority item |
| Main classes | ArrayDeque, LinkedList | ArrayDeque, LinkedList | PriorityQueue itself |
| offer / poll | O(1) | O(1) | O(log n) |
| null allowed | Depends on class | Not in ArrayDeque | No |
| Real life | Ticket line | Line with front entry for seniors | Emergency room |
Differences between ArrayDeque and LinkedList as a queue
| Feature | ArrayDeque | LinkedList |
|---|---|---|
| Internal structure | Resizable circular array | Doubly linked nodes |
| offer / poll speed | Faster (cache friendly) | Slower (allocates a node per item) |
| Memory per item | Low | High (node + two links) |
| null elements | Not allowed | Allowed |
| Also a List? | No | Yes (get(i), add(i, e)) |
| Thread-safe | No | No |
| Recommended as a queue | Yes | Only when you need null or List methods |
Differences between queue and stack
| Feature | Queue | Stack |
|---|---|---|
| Order | FIFO — First In, First Out | LIFO — Last In, First Out |
| Ends used | Add at rear, remove from front | Add and remove at the top |
| Add | offer / add | push |
| Remove | poll / remove | pop |
| Look | peek (front) | peek (top) |
| Java choice | Queue<E> q = new ArrayDeque<>() | Deque<E> s = new ArrayDeque<>() |
| Graph search | Breadth-first search (BFS) | Depth-first search (DFS) |
| Real life | Ticket counter line | Stack of plates |
Advanced — Queue / Deque
Build a circular queue with an array
- A simple array queue wastes space: after polling, the front slots stay empty. A circular queue wraps around and reuses them.
- Keep a
frontindex and asize. The rear position is(front + size) % capacity; polling movesfront = (front + 1) % capacity. ArrayDequeworks the same way internally (head and tail indexes on a circular array) and grows when full.- Real life: a revolving sushi conveyor belt — plates go round and empty spots are refilled.
| Operation | Array (capacity 3) | front | size | Result |
|---|---|---|---|---|
| offer(1) | [1, _, _] | 0 | 1 | true |
| offer(2) | [1, 2, _] | 0 | 2 | true |
| offer(3) | [1, 2, 3] | 0 | 3 | true |
| offer(4) | [1, 2, 3] | 0 | 3 | false (full) |
| poll() | [_, 2, 3] | 1 | 2 | 1 |
| offer(4) | [4, 2, 3] | 1 | 3 | true (wrapped to index 0) |
| poll() | [4, _, 3] | 2 | 2 | 2 |
public class CircularQueue {
private final int[] data;
private int front = 0; // index of the first item
private int size = 0;
CircularQueue(int capacity) {
data = new int[capacity];
}
boolean offer(int x) {
if (size == data.length) return false; // full
int rear = (front + size) % data.length; // wraps around
data[rear] = x;
size++;
return true;
}
Integer poll() {
if (size == 0) return null; // empty
int x = data[front];
front = (front + 1) % data.length;
size--;
return x;
}
Integer peek() {
return size == 0 ? null : data[front];
}
public static void main(String[] args) {
CircularQueue belt = new CircularQueue(3);
belt.offer(1);
belt.offer(2);
belt.offer(3);
System.out.println(belt.offer(4)); // false: full
System.out.println(belt.poll()); // 1
System.out.println(belt.offer(4)); // true: reuses index 0
System.out.println(belt.poll() + " " + belt.poll() + " " + belt.poll()); // 2 3 4
System.out.println(belt.poll()); // null
}
} How PriorityQueue works internally
PriorityQueueis a binary min-heap stored in an array. Every parent is smaller than (or equal to) its children, so the smallest item is always at index 0.offerputs the item at the end and sifts it up;pollmoves the last item to the root and sifts it down. Both take O(log n).- Real life: a company hierarchy where every manager is more senior than their team — the CEO (the top priority) is always at the top.
| Item | Formula or cost | Meaning |
|---|---|---|
| Parent of index i | (i - 1) / 2 | Where to compare when sifting up |
| Left child of i | 2 * i + 1 | Where to look when sifting down |
| Right child of i | 2 * i + 2 | Where to look when sifting down |
peek() | O(1) | Root is the smallest |
offer(e) | O(log n) | Add at end, sift up |
poll() | O(log n) | Move last to root, sift down |
remove(o) / contains(o) | O(n) | Linear search through the array |
| Build from a collection | O(n) | Heapify in one pass |
import java.util.PriorityQueue;
public class HeapInside {
public static void main(String[] args) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int x : new int[] { 50, 30, 40, 10, 20 }) {
heap.offer(x);
System.out.println("offer " + x + " -> " + heap);
}
// offer 50 -> [50]
// offer 30 -> [30, 50]
// offer 40 -> [30, 50, 40]
// offer 10 -> [10, 30, 40, 50]
// offer 20 -> [10, 20, 40, 50, 30]
System.out.print("poll order: ");
while (!heap.isEmpty()) System.out.print(heap.poll() + " "); // 10 20 30 40 50
System.out.println();
}
} Top K items with a heap
- To find the K largest items, keep a min-heap of size K. Offer each item; if the heap grows beyond K, poll the smallest.
- This takes O(n log K) time and O(K) memory — far better than sorting millions of items.
- Real life: a food delivery app showing the top 3 most-ordered dishes of the day.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class TopDishes {
record Dish(String name, int orders) { }
public static void main(String[] args) {
List<Dish> dishes = List.of(
new Dish("Biryani", 950), new Dish("Dosa", 720), new Dish("Pizza", 860),
new Dish("Noodles", 430), new Dish("Paneer", 610), new Dish("Burger", 880));
int k = 3;
PriorityQueue<Dish> top = new PriorityQueue<>(Comparator.comparingInt(Dish::orders)); // min-heap
for (Dish d : dishes) {
top.offer(d);
if (top.size() > k) top.poll(); // drop the smallest, keep the best k
}
List<Dish> result = new ArrayList<>(top);
result.sort(Comparator.comparingInt(Dish::orders).reversed());
result.forEach(d -> System.out.println(d.name() + " " + d.orders()));
// Biryani 950
// Burger 880
// Pizza 860
}
} Breadth-first search with a queue
- Breadth-first search (BFS) explores a graph level by level: first all direct neighbours, then their neighbours, and so on.
- The queue guarantees nearer items are processed before farther ones, so BFS finds the shortest path in an unweighted graph.
- Real life: a social network finding friends (level 1), friends of friends (level 2), and so on for "People you may know".
import java.util.ArrayDeque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class FriendLevels {
public static void main(String[] args) {
Map<String, List<String>> friends = Map.of(
"You", List.of("Asha", "Ravi"),
"Asha", List.of("You", "Kiran", "Meena"),
"Ravi", List.of("You", "Meena"),
"Kiran", List.of("Asha", "Zoya"),
"Meena", List.of("Asha", "Ravi"),
"Zoya", List.of("Kiran")
);
Map<String, Integer> level = new LinkedHashMap<>();
Queue<String> queue = new ArrayDeque<>();
queue.offer("You");
level.put("You", 0);
while (!queue.isEmpty()) {
String person = queue.poll();
for (String f : friends.get(person)) {
if (!level.containsKey(f)) { // not visited yet
level.put(f, level.get(person) + 1);
queue.offer(f);
}
}
}
System.out.println(level); // {You=0, Asha=1, Ravi=1, Kiran=2, Meena=2, Zoya=3}
}
} BlockingQueue and producer-consumer
- A
BlockingQueueis a thread-safe queue whoseputwaits when the queue is full and whosetakewaits when it is empty. - This makes the producer-consumer pattern easy: producers
putwork, consumerstakeit, and no manualwait/notifyis needed. - A special "poison pill" item tells the consumer to stop.
- Real life: a restaurant pickup shelf. The kitchen (producer) waits if the shelf is full; the delivery rider (consumer) waits if it is empty.
| Action | Throws | Special value | Blocks | Times out |
|---|---|---|---|---|
| Insert | add(e) | offer(e) | put(e) | offer(e, time, unit) |
| Remove | remove() | poll() | take() | poll(time, unit) |
| Examine | element() | peek() | — | — |
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class FoodDelivery {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> shelf = new ArrayBlockingQueue<>(2); // pickup shelf holds 2 orders
Thread kitchen = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
shelf.put("Order-" + i); // waits if the shelf is full
System.out.println("Kitchen packed Order-" + i);
}
shelf.put("DONE"); // poison pill: no more orders
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread rider = new Thread(() -> {
try {
while (true) {
String order = shelf.take(); // waits if the shelf is empty
if (order.equals("DONE")) break;
System.out.println("Rider picked " + order);
Thread.sleep(100); // delivering
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
kitchen.start();
rider.start();
kitchen.join();
rider.join();
System.out.println("All orders delivered");
}
} Concurrent queues
ArrayDeque,LinkedList, andPriorityQueueare not thread-safe. For queues shared between threads, use a class fromjava.util.concurrent.- Real life: a ride-hailing app where many customers book rides and many drivers accept them at the same time.
| Class | Bounded? | Blocking? | Best for |
|---|---|---|---|
ConcurrentLinkedQueue | No | No (lock-free) | Fast shared FIFO without waiting |
ArrayBlockingQueue | Yes (fixed) | Yes | Producer-consumer with back-pressure |
LinkedBlockingQueue | Optional | Yes | Thread pool task queues |
PriorityBlockingQueue | No | Yes (take waits) | Shared priority jobs |
DelayQueue | No | Yes | Items available only after a delay (OTP expiry, reminders) |
SynchronousQueue | Zero capacity | Yes | Direct hand-off from one thread to another |
LinkedTransferQueue | No | Yes | Producer can wait until a consumer receives |
ConcurrentLinkedDeque | No | No (lock-free) | Shared deque or stack |
Sliding window maximum with a Deque
- Keep indexes in a deque whose values decrease from front to rear. Drop indexes that leave the window from the front, and smaller values from the rear.
- The front always holds the maximum of the current window, so the whole array is processed in O(n).
- Real life: a weather report showing the highest temperature of every 3-day window.
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class WindowMax {
static int[] maxInWindows(int[] a, int k) {
int[] result = new int[a.length - k + 1];
Deque<Integer> dq = new ArrayDeque<>(); // indexes, values decreasing
for (int i = 0; i < a.length; i++) {
if (!dq.isEmpty() && dq.peekFirst() <= i - k) dq.pollFirst(); // left the window
while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast(); // smaller values are useless now
dq.offerLast(i);
if (i >= k - 1) result[i - k + 1] = a[dq.peekFirst()];
}
return result;
}
public static void main(String[] args) {
int[] temps = { 31, 35, 33, 30, 36, 32, 29, 34 };
System.out.println(Arrays.toString(maxInWindows(temps, 3))); // [35, 35, 36, 36, 36, 34]
}
} Time complexity of queue operations
| Operation | ArrayDeque | LinkedList | PriorityQueue | ArrayBlockingQueue | ConcurrentLinkedQueue |
|---|---|---|---|---|---|
| offer / add | O(1) amortized | O(1) | O(log n) | O(1) | O(1) |
| poll / remove() | O(1) | O(1) | O(log n) | O(1) | O(1) |
| peek / element | O(1) | O(1) | O(1) | O(1) | O(1) |
| contains / remove(o) | O(n) | O(n) | O(n) | O(n) | O(n) |
| size() | O(1) | O(1) | O(1) | O(1) | O(n) (counts nodes) |
Queue best practices
| Practice | Why |
|---|---|
Use Queue<E> q = new ArrayDeque<>(); by default | Fast and memory efficient |
Prefer offer, poll, peek in normal code | They return false or null instead of throwing |
Check poll() and peek() results for null | They return null when the queue is empty |
Never store null in ArrayDeque or PriorityQueue | Both throw NullPointerException |
Do not expect sorted output when printing a PriorityQueue | Only poll returns items in priority order |
| Do not change fields used by the Comparator while queued | It corrupts the heap; remove, change, then offer again |
| Add a sequence number for FIFO among equal priorities | PriorityQueue does not keep arrival order for ties |
Use a BlockingQueue for producer-consumer | No manual wait/notify code |
| Use a queue (not a stack) for BFS | A stack would give DFS order instead |
Tricky Interview Points
Q1) What is a queue?
Answer A linear data structure that follows FIFO: items are added at the rear and removed from the front, so the item that waited longest is served first.
Q2) What is the difference between offer and add?
Answer Both insert at the rear. On a full bounded queue, add throws IllegalStateException while offer returns false. On unbounded queues like ArrayDeque both succeed.
Q3) What is the difference between poll and remove?
Answer Both remove the front item. On an empty queue, poll returns null while remove() throws NoSuchElementException.
Q4) What is the difference between peek and element?
Answer Both return the front item without removing it. On an empty queue, peek returns null while element throws NoSuchElementException.
Q5) Which class should you use for a queue in Java?
Answer ArrayDeque for single-threaded FIFO queues, PriorityQueue when items must come out by priority, and a BlockingQueue or ConcurrentLinkedQueue when threads share the queue.
Q6) ArrayDeque vs LinkedList as a queue?
Answer ArrayDeque uses a circular array: faster, less memory, no null elements. LinkedList uses nodes: more memory, allows null, and also implements List. Prefer ArrayDeque.
Q7) What is a Deque?
Answer A double-ended queue that supports insertion and removal at both ends (offerFirst, offerLast, pollFirst, pollLast). It can be used as a queue, a stack, or both.
Q8) How does PriorityQueue work?
Answer It is a binary heap stored in an array. The smallest item (or highest priority by Comparator) is at the root. offer sifts up and poll sifts down in O(log n); peek is O(1).
Q9) Is a PriorityQueue sorted?
Answer No. Only the head is guaranteed to be the smallest. Iterating or printing shows heap order. To get sorted output, poll repeatedly.
Q10) How do you create a max-heap in Java?
Answer new PriorityQueue<>(Comparator.reverseOrder()) for natural ordering, or pass a reversed custom Comparator.
Q11) Does PriorityQueue keep FIFO order for equal priorities?
Answer No, ties come out in no guaranteed order. Add an increasing sequence number and use it as a tie-breaker in the Comparator.
Q12) What is a circular queue?
Answer An array-based queue whose front and rear indexes wrap around using modulo, so slots freed by polling are reused. ArrayDeque uses this idea internally.
Q13) What is a BlockingQueue?
Answer A thread-safe queue from java.util.concurrent where put waits while the queue is full and take waits while it is empty. It is the standard tool for producer-consumer designs.
Q14) Explain the producer-consumer problem.
Answer Producers create work and consumers process it at different speeds. A bounded BlockingQueue between them makes producers wait when it is full and consumers wait when it is empty, without manual wait and notify.
Q15) Why is a queue used in BFS?
Answer BFS must visit nodes in order of distance from the start. A FIFO queue processes all nodes at distance d before any at distance d + 1, which also gives shortest paths in unweighted graphs.
Q16) What is the difference between a queue and a stack?
Answer A queue is FIFO (add at rear, remove from front); a stack is LIFO (add and remove at the top). Queues power BFS and scheduling; stacks power DFS, undo, and recursion.
Q17) How do you implement a queue using two stacks?
Answer Push incoming items onto an in-stack. To poll, if the out-stack is empty, move everything from the in-stack to the out-stack, then pop from the out-stack. Each item moves at most twice, giving amortized O(1).
Q18) Why do ArrayDeque and PriorityQueue reject null?
Answer Their poll and peek methods return null to mean the queue is empty, so a null element would be ambiguous.
Q19) How do you find the K largest elements efficiently?
Answer Keep a min-heap of size K. Offer each element and poll whenever the size exceeds K. The heap then holds the K largest in O(n log K) time.
Q20) What is the time complexity of size() in ConcurrentLinkedQueue?
Answer O(n), because it walks the nodes to count them and the result may already be stale in a concurrent setting. Prefer isEmpty() for checks.
Simple Programs
Ticket counter waiting time simulation
import java.util.ArrayDeque;
import java.util.Queue;
public class CounterSimulation {
record Customer(String name, int arrival, int service) { } // minutes
public static void main(String[] args) {
Queue<Customer> line = new ArrayDeque<>();
line.offer(new Customer("Asha", 0, 4));
line.offer(new Customer("Ravi", 1, 3));
line.offer(new Customer("Kiran", 2, 5));
line.offer(new Customer("Meena", 10, 2));
int clock = 0;
int totalWait = 0;
int served = 0;
while (!line.isEmpty()) {
Customer c = line.poll();
clock = Math.max(clock, c.arrival()); // counter may be idle
int wait = clock - c.arrival();
System.out.println(c.name() + " waits " + wait + " min, served at minute " + clock);
totalWait += wait;
clock += c.service();
served++;
}
System.out.println("Average wait: " + (double) totalWait / served + " min");
// Asha waits 0 min, served at minute 0
// Ravi waits 3 min, served at minute 4
// Kiran waits 5 min, served at minute 7
// Meena waits 2 min, served at minute 12
// Average wait: 2.5 min
}
} Office printer queue with urgent jobs
import java.util.Comparator;
import java.util.PriorityQueue;
public class PrinterQueue {
record Job(String file, boolean urgent, long seq) { }
private final PriorityQueue<Job> jobs = new PriorityQueue<>(
Comparator.comparing((Job j) -> !j.urgent()) // urgent jobs first
.thenComparingLong(Job::seq)); // same priority: first come, first served
private long counter = 0;
void submit(String file, boolean urgent) {
jobs.offer(new Job(file, urgent, counter++));
}
public static void main(String[] args) {
PrinterQueue printer = new PrinterQueue();
printer.submit("notes.pdf", false);
printer.submit("salary-slips.pdf", true);
printer.submit("poster.png", false);
printer.submit("exam-paper.docx", true);
while (!printer.jobs.isEmpty()) {
System.out.println("Printing " + printer.jobs.poll().file());
}
// Printing salary-slips.pdf
// Printing exam-paper.docx
// Printing notes.pdf
// Printing poster.png
}
} Hot potato game (Josephus problem)
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
public class HotPotato {
static String winner(List<String> kids, int passes) {
Queue<String> circle = new ArrayDeque<>(kids);
while (circle.size() > 1) {
for (int i = 1; i < passes; i++) {
circle.offer(circle.poll()); // pass the potato to the next kid
}
System.out.println(circle.poll() + " is out"); // holding the potato when music stops
}
return circle.poll();
}
public static void main(String[] args) {
String w = winner(List.of("Anu", "Bala", "Chinni", "Deepu", "Eshu"), 3);
System.out.println("Winner: " + w);
// Chinni is out
// Anu is out
// Eshu is out
// Bala is out
// Winner: Deepu
}
} OTP rate limiter with a sliding time window
import java.util.ArrayDeque;
import java.util.Deque;
public class RateLimiter {
private final Deque<Long> times = new ArrayDeque<>();
private final int limit;
private final long windowMs;
RateLimiter(int limit, long windowMs) {
this.limit = limit;
this.windowMs = windowMs;
}
boolean allow(long now) {
while (!times.isEmpty() && times.peekFirst() <= now - windowMs) {
times.pollFirst(); // forget requests outside the window
}
if (times.size() >= limit) return false;
times.offerLast(now);
return true;
}
public static void main(String[] args) {
RateLimiter otp = new RateLimiter(3, 10_000); // max 3 OTPs per 10 seconds
long[] requests = { 0, 2_000, 4_000, 6_000, 10_500, 12_000 };
for (long t : requests) {
System.out.println("t=" + t / 1000.0 + "s -> " + (otp.allow(t) ? "OTP sent" : "Too many requests"));
}
// t=0.0s -> OTP sent
// t=2.0s -> OTP sent
// t=4.0s -> OTP sent
// t=6.0s -> Too many requests
// t=10.5s -> OTP sent
// t=12.0s -> OTP sent
}
} Shortest path for a warehouse robot (BFS on a grid)
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
public class WarehouseRobot {
static int shortestPath(String[] grid) {
int rows = grid.length;
int cols = grid[0].length();
int[][] dist = new int[rows][cols];
for (int[] row : dist) Arrays.fill(row, -1);
int[][] moves = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[] { 0, 0 });
dist[0][0] = 0;
while (!q.isEmpty()) {
int[] cell = q.poll();
int r = cell[0];
int c = cell[1];
if (r == rows - 1 && c == cols - 1) return dist[r][c];
for (int[] m : moves) {
int nr = r + m[0];
int nc = c + m[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols
&& grid[nr].charAt(nc) == '.' && dist[nr][nc] == -1) {
dist[nr][nc] = dist[r][c] + 1;
q.offer(new int[] { nr, nc });
}
}
}
return -1; // no path
}
public static void main(String[] args) {
String[] warehouse = { // # = shelf, . = free aisle
"..#....",
".##.##.",
"....#..",
"#.#...#",
"...#..."
};
System.out.println("Steps from dock to packing desk: " + shortestPath(warehouse)); // 10
}
} First non-repeating character in a live chat stream
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
public class FirstUniqueInStream {
public static void main(String[] args) {
String stream = "aabcbd"; // characters arriving one by one
Map<Character, Integer> count = new HashMap<>();
Queue<Character> candidates = new ArrayDeque<>();
StringBuilder out = new StringBuilder();
for (char c : stream.toCharArray()) {
count.merge(c, 1, Integer::sum);
candidates.offer(c);
while (!candidates.isEmpty() && count.get(candidates.peek()) > 1) {
candidates.poll(); // front repeated: no longer unique
}
out.append(candidates.isEmpty() ? '#' : candidates.peek()).append(' ');
}
System.out.println(out.toString().trim()); // a # b b c c (# = none)
}
} Generate binary numbers 1 to N with a queue
import java.util.ArrayDeque;
import java.util.Queue;
public class BinaryNumbers {
public static void main(String[] args) {
int n = 8;
Queue<String> q = new ArrayDeque<>();
q.offer("1");
for (int i = 1; i <= n; i++) {
String s = q.poll();
System.out.print(s + " ");
q.offer(s + "0"); // children of s in BFS order
q.offer(s + "1");
}
System.out.println();
// 1 10 11 100 101 110 111 1000
}
} Problem Solving Tricks
- FIFO = First In, First Out. Picture a ticket counter line.
- Default queue:
Queue<E> q = new ArrayDeque<>();— notLinkedList, notStack. - Remember the pairs: add/offer, remove/poll, element/peek — the first throws, the second returns false or null.
- Need "most important first"? Use
PriorityQueue; for largest first,Comparator.reverseOrder(). - Printing a
PriorityQueueis not sorted — poll to get sorted order. - Round robin =
q.offer(q.poll()). - Shortest path in an unweighted grid or graph = BFS with a queue.
- Top K largest = min-heap of size K; top K smallest = max-heap of size K.
- Threads sharing work?
BlockingQueuewithputandtake. - Sliding window maximum or minimum = monotonic
Deque, O(n).
Practice Programs List
- Simulate a ticket counter: offer 5 names, serve 2, and print who is next.
- Show the difference between
add/offer,remove/poll, andelement/peekwith anArrayBlockingQueueof size 2. - Build a bank token system that issues and calls tokens in order.
- Use a
Dequeto model a line where seniors join at the front. - Create a hospital emergency queue with
PriorityQueueand aComparatoron severity. - Print a
PriorityQueue, then poll it, and explain why the outputs differ. - Build a printer queue where urgent jobs go first and equal jobs keep arrival order.
- Simulate round-robin turns for 4 players over 10 turns.
- Implement a fixed-size circular queue with an array.
- Implement a queue using two stacks.
- Find the top 3 highest scores from a list using a min-heap of size 3.
- Use BFS to find the shortest path in a maze grid.
- Write a producer-consumer program with
ArrayBlockingQueue,put, andtake. - Find the maximum of every 3-day window of temperatures using a
Deque.