Skip to main content

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.

L1

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), and peek (see who is at the front).
  • In Java, Queue is an interface. Use Queue<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

OperationWhat it doesThrows an exceptionReturns a special value
InsertAdds an item at the rearadd(e) — IllegalStateException if a bounded queue is fulloffer(e) — returns false if full
RemoveRemoves and returns the front itemremove() — NoSuchElementException if emptypoll() — returns null if empty
ExamineReturns the front item without removing itelement() — NoSuchElementException if emptypeek() — returns null if empty
Check emptyTrue if there are no items—isEmpty()
CountNumber 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.

Java queue operations in six steps on a three-slot track with front on the left and rear on the right: 1 empty queue; 2 offer(10) puts 10 at the front; 3 offer(20) puts 20 behind 10; 4 offer(30) puts 30 at the rear; 5 peek() highlights 10 at the front and it stays; 6 poll() removes 10 from the front, leaving 20 and 30. A side card compares offer and poll to joining and being served in a ticket counter line, and a footer notes that offer, poll, and peek all take O(1) time.
Java queue operations — items join at the rear and leave from the front: three offers, a peek, and a poll
  • offer(e): adds e at the rear — returns false only 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() and poll() return null instead of throwing.

Real-life examples of queue

Real-life scenariooffer meanspoll means
Railway ticket counterA passenger joins the lineThe front passenger gets a ticket
Bank token systemA token is issuedThe next token is called to the counter
Office printerA document is sent to printThe printer prints the oldest job
Call centreA caller is put on holdThe next free agent takes the oldest call
Toll plaza laneA car arrives at the boothThe front car pays and leaves
Food delivery appA customer places an orderThe kitchen prepares the oldest order
Chat messagesA message is sentMessages are delivered in the order sent
Music playlist "play next"A song is added to the queueThe next song starts playing
CPU schedulingA process becomes readyThe scheduler runs the next process
Keyboard bufferA key is pressedThe 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 (false or null).
  • Use offer, poll, and peek in normal application code; use add, remove, and element when failure means a bug.
  • For unbounded queues like ArrayDeque, add and offer both always succeed. The difference shows on bounded queues.
  • Real life: a parking lot with only 2 slots. A polite guard says "full" (offer returns false); a strict guard raises an alarm (add throws).
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

ClassOrderBounded?Thread-safe?Real-life use
ArrayDequeFIFONo (grows)NoTicket line, BFS, task list
LinkedListFIFONoNoQueue that must allow null
PriorityQueueBy priority (smallest first)NoNoHospital emergency room
ArrayBlockingQueueFIFOYes (fixed)Yes, blockingPickup shelf with limited space
LinkedBlockingQueueFIFOOptionalYes, blockingThread pool work queue
ConcurrentLinkedQueueFIFONoYes, lock-freeHigh-traffic event logging
PriorityBlockingQueueBy priorityNoYes, blockingShared priority job scheduler
DelayQueueBy expiry timeNoYes, blockingReminders 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

  • ArrayDeque is the fastest general-purpose queue: a resizable circular array with O(1) offer and poll.
  • Declare it as Queue<E> so only queue methods are visible. offer adds at the tail and poll removes from the head.
  • ArrayDeque does not allow null, because poll and peek use null to 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.
WayOrderRemoves items?
for-each / forEachFront to rearNo
while (!q.isEmpty()) q.poll()Front to rearYes (drains the queue)
removeIf(condition)—Removes matching items only
Iterator with remove()Front to rearOnly the ones you remove
for-each on a PriorityQueueHeap 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.
  • ArrayDeque and LinkedList implement Deque. 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.
ActionFront — throwsFront — special valueRear — throwsRear — special value
InsertaddFirst(e)offerFirst(e)addLast(e)offerLast(e)
RemoveremoveFirst()pollFirst()removeLast()pollLast()
ExaminegetFirst()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

  • PriorityQueue does not serve in arrival order. It always gives the highest-priority item first — by default the smallest (min-heap).
  • Give it a Comparator to define priority for your own objects. offer and poll are O(log n); peek is O(1).
  • Printing or iterating a PriorityQueue is NOT sorted — only repeated poll gives sorted order. It does not allow null.
  • 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

FeatureQueueDequePriorityQueue
TypeInterfaceInterface (extends Queue)Class (implements Queue)
OrderFIFOFIFO, LIFO, or bothBy priority (Comparator)
Insert atRear onlyFront or rearIts heap position
Remove fromFront onlyFront or rearHighest priority item
Main classesArrayDeque, LinkedListArrayDeque, LinkedListPriorityQueue itself
offer / pollO(1)O(1)O(log n)
null allowedDepends on classNot in ArrayDequeNo
Real lifeTicket lineLine with front entry for seniorsEmergency room

Differences between ArrayDeque and LinkedList as a queue

FeatureArrayDequeLinkedList
Internal structureResizable circular arrayDoubly linked nodes
offer / poll speedFaster (cache friendly)Slower (allocates a node per item)
Memory per itemLowHigh (node + two links)
null elementsNot allowedAllowed
Also a List?NoYes (get(i), add(i, e))
Thread-safeNoNo
Recommended as a queueYesOnly when you need null or List methods

Differences between queue and stack

FeatureQueueStack
OrderFIFO — First In, First OutLIFO — Last In, First Out
Ends usedAdd at rear, remove from frontAdd and remove at the top
Addoffer / addpush
Removepoll / removepop
Lookpeek (front)peek (top)
Java choiceQueue<E> q = new ArrayDeque<>()Deque<E> s = new ArrayDeque<>()
Graph searchBreadth-first search (BFS)Depth-first search (DFS)
Real lifeTicket counter lineStack of plates
L2

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 front index and a size. The rear position is (front + size) % capacity; polling moves front = (front + 1) % capacity.
  • ArrayDeque works 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.
OperationArray (capacity 3)frontsizeResult
offer(1)[1, _, _]01true
offer(2)[1, 2, _]02true
offer(3)[1, 2, 3]03true
offer(4)[1, 2, 3]03false (full)
poll()[_, 2, 3]121
offer(4)[4, 2, 3]13true (wrapped to index 0)
poll()[4, _, 3]222
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

  • PriorityQueue is 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.
  • offer puts the item at the end and sifts it up; poll moves 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.
ItemFormula or costMeaning
Parent of index i(i - 1) / 2Where to compare when sifting up
Left child of i2 * i + 1Where to look when sifting down
Right child of i2 * i + 2Where 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 collectionO(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 BlockingQueue is a thread-safe queue whose put waits when the queue is full and whose take waits when it is empty.
  • This makes the producer-consumer pattern easy: producers put work, consumers take it, and no manual wait/notify is 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.
ActionThrowsSpecial valueBlocksTimes out
Insertadd(e)offer(e)put(e)offer(e, time, unit)
Removeremove()poll()take()poll(time, unit)
Examineelement()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, and PriorityQueue are not thread-safe. For queues shared between threads, use a class from java.util.concurrent.
  • Real life: a ride-hailing app where many customers book rides and many drivers accept them at the same time.
ClassBounded?Blocking?Best for
ConcurrentLinkedQueueNoNo (lock-free)Fast shared FIFO without waiting
ArrayBlockingQueueYes (fixed)YesProducer-consumer with back-pressure
LinkedBlockingQueueOptionalYesThread pool task queues
PriorityBlockingQueueNoYes (take waits)Shared priority jobs
DelayQueueNoYesItems available only after a delay (OTP expiry, reminders)
SynchronousQueueZero capacityYesDirect hand-off from one thread to another
LinkedTransferQueueNoYesProducer can wait until a consumer receives
ConcurrentLinkedDequeNoNo (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

OperationArrayDequeLinkedListPriorityQueueArrayBlockingQueueConcurrentLinkedQueue
offer / addO(1) amortizedO(1)O(log n)O(1)O(1)
poll / remove()O(1)O(1)O(log n)O(1)O(1)
peek / elementO(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

PracticeWhy
Use Queue<E> q = new ArrayDeque<>(); by defaultFast and memory efficient
Prefer offer, poll, peek in normal codeThey return false or null instead of throwing
Check poll() and peek() results for nullThey return null when the queue is empty
Never store null in ArrayDeque or PriorityQueueBoth throw NullPointerException
Do not expect sorted output when printing a PriorityQueueOnly poll returns items in priority order
Do not change fields used by the Comparator while queuedIt corrupts the heap; remove, change, then offer again
Add a sequence number for FIFO among equal prioritiesPriorityQueue does not keep arrival order for ties
Use a BlockingQueue for producer-consumerNo manual wait/notify code
Use a queue (not a stack) for BFSA stack would give DFS order instead
L3

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.

L4

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
    }
}
L5

Problem Solving Tricks

  • FIFO = First In, First Out. Picture a ticket counter line.
  • Default queue: Queue<E> q = new ArrayDeque<>(); — not LinkedList, not Stack.
  • 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 PriorityQueue is 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? BlockingQueue with put and take.
  • Sliding window maximum or minimum = monotonic Deque, O(n).
L6

Practice Programs List

  1. Simulate a ticket counter: offer 5 names, serve 2, and print who is next.
  2. Show the difference between add/offer, remove/poll, and element/peek with an ArrayBlockingQueue of size 2.
  3. Build a bank token system that issues and calls tokens in order.
  4. Use a Deque to model a line where seniors join at the front.
  5. Create a hospital emergency queue with PriorityQueue and a Comparator on severity.
  6. Print a PriorityQueue, then poll it, and explain why the outputs differ.
  7. Build a printer queue where urgent jobs go first and equal jobs keep arrival order.
  8. Simulate round-robin turns for 4 players over 10 turns.
  9. Implement a fixed-size circular queue with an array.
  10. Implement a queue using two stacks.
  11. Find the top 3 highest scores from a list using a min-heap of size 3.
  12. Use BFS to find the shortest path in a maze grid.
  13. Write a producer-consumer program with ArrayBlockingQueue, put, and take.
  14. Find the maximum of every 3-day window of temperatures using a Deque.