1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Priority Queue
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
07Hrs
36Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Priority Queue

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
07Hrs
36Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
    • Java + DSA
    • Full Stack Web Dev
    • AI/ML + Python
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Priority Queue

Overview

A standard Queue follows strict FIFO: first in, first out. But what if you are in an emergency room? A patient with a paper cut who arrived first should NOT be treated before a patient with a heart attack who arrived second. This is where a Priority Queue is used.

A Priority Queue acts like a regular queue, but every element has a 'priority' associated with it. When you call poll(), it does not return the oldest element; it returns the element with the highest priority (or lowest priority, depending on configuration).

Under the hood, Java's PriorityQueue does NOT sort an array. It uses a Binary Min-Heap data structure. This allows it to find the minimum/maximum element in O(1) time, and insert or delete elements in O(log N) time. It is significantly faster than inserting into an array and sorting it (O(N log N)).

Syntax

Using Java's PriorityQueue
java
import java.util.PriorityQueue;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        // 1. Default Min-Heap (Smallest numbers come out first)
        PriorityQueue<Integer> minPQ = new PriorityQueue<>();
        minPQ.offer(50);
        minPQ.offer(10);
        minPQ.offer(30);
        
        System.out.println(minPQ.poll()); // 10 (Smallest first!)
        
        // 2. Max-Heap (Largest numbers come out first)
        // We pass a Comparator to reverse the natural order
        PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder());
        maxPQ.offer(50);
        maxPQ.offer(10);
        maxPQ.offer(30);
        
        System.out.println(maxPQ.poll()); // 50 (Largest first!)
        
        // 3. Custom Objects (Requires Comparable or Comparator)
        PriorityQueue<Patient> erQueue = new PriorityQueue<>((p1, p2) -> 
            Integer.compare(p2.severity, p1.severity) // Higher severity first
        );
        erQueue.offer(new Patient("Alice", 2)); // Paper cut
        erQueue.offer(new Patient("Bob", 10));  // Heart attack
        
        System.out.println(erQueue.poll().name); // Bob is treated first
    }
}

Common Pitfalls

  • Assuming iteration order is sorted. If you do for (int x : pq) { System.out.println(x); }, the output will NOT be perfectly sorted! A heap only guarantees that the root is the minimum. To get sorted output, you must poll() in a while loop until empty.
  • Forgetting to provide a Comparator for custom objects. If you create a PriorityQueue<Student> and Student does not implement the Comparable interface, the moment you offer() the second student, Java will crash with a ClassCastException because it doesn't know how to compare them.
  • Using remove(Object) instead of poll(). While poll() removes the root in O(log N) time, searching for a specific object in the middle of a heap and removing it is an O(N) operation because heaps are not built for random searching.

Interview Questions

What is the time complexity of offer() and poll() in a Priority Queue?

Both offer() (insertion) and poll() (removal) run in O(log N) time. This is because adding or removing requires 'bubbling up' or 'sifting down' the tree to restore the heap property. Finding the minimum (peek()) is O(1).

How would you find the Kth largest element in an array of N elements?

Using a Min-Heap Priority Queue of size K. Iterate through the array, adding elements to the PQ. If the PQ size exceeds K, poll() the smallest element out. At the end of the array, the PQ holds the K largest elements, and the root (peek()) is exactly the Kth largest. This takes O(N log K) time, which is much faster than sorting the whole array O(N log N).

Real-World Example

Dijkstra's Algorithm for GPS navigation uses a Priority Queue. When exploring routes to a destination, the algorithm always wants to explore the 'currently known shortest path' next. A Priority Queue instantly provides the node with the lowest travel cost at every step.

example
java
PriorityQueue<RouteNode> pq = new PriorityQueue<>(
    (a, b) -> Integer.compare(a.costFromStart, b.costFromStart)
);

// Add the starting city
pq.offer(new RouteNode("New York", 0));

while (!pq.isEmpty()) {
    // O(1) to find, O(log N) to extract the cheapest path so far
    RouteNode cheapest = pq.poll(); 
    
    if (cheapest.city.equals(destination)) {
        return cheapest.costFromStart; // Found the shortest route!
    }
    
    // Explore neighbors...
}

Check Your Knowledge

Test your understanding of Priority Queue with these quick questions.

Question 1

By default, what type of element does Java's PriorityQueue return first?

Question 2

What is the time complexity of removing the highest priority element (`poll()`)?

Question 3

If you iterate over a PriorityQueue using a for-each loop, what order will the elements be in?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Priority Queue

Overview

A standard Queue follows strict FIFO: first in, first out. But what if you are in an emergency room? A patient with a paper cut who arrived first should NOT be treated before a patient with a heart attack who arrived second. This is where a Priority Queue is used.

A Priority Queue acts like a regular queue, but every element has a 'priority' associated with it. When you call poll(), it does not return the oldest element; it returns the element with the highest priority (or lowest priority, depending on configuration).

Under the hood, Java's PriorityQueue does NOT sort an array. It uses a Binary Min-Heap data structure. This allows it to find the minimum/maximum element in O(1) time, and insert or delete elements in O(log N) time. It is significantly faster than inserting into an array and sorting it (O(N log N)).

Syntax

Using Java's PriorityQueue
java
import java.util.PriorityQueue;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        // 1. Default Min-Heap (Smallest numbers come out first)
        PriorityQueue<Integer> minPQ = new PriorityQueue<>();
        minPQ.offer(50);
        minPQ.offer(10);
        minPQ.offer(30);
        
        System.out.println(minPQ.poll()); // 10 (Smallest first!)
        
        // 2. Max-Heap (Largest numbers come out first)
        // We pass a Comparator to reverse the natural order
        PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder());
        maxPQ.offer(50);
        maxPQ.offer(10);
        maxPQ.offer(30);
        
        System.out.println(maxPQ.poll()); // 50 (Largest first!)
        
        // 3. Custom Objects (Requires Comparable or Comparator)
        PriorityQueue<Patient> erQueue = new PriorityQueue<>((p1, p2) -> 
            Integer.compare(p2.severity, p1.severity) // Higher severity first
        );
        erQueue.offer(new Patient("Alice", 2)); // Paper cut
        erQueue.offer(new Patient("Bob", 10));  // Heart attack
        
        System.out.println(erQueue.poll().name); // Bob is treated first
    }
}

Common Pitfalls

  • Assuming iteration order is sorted. If you do for (int x : pq) { System.out.println(x); }, the output will NOT be perfectly sorted! A heap only guarantees that the root is the minimum. To get sorted output, you must poll() in a while loop until empty.
  • Forgetting to provide a Comparator for custom objects. If you create a PriorityQueue<Student> and Student does not implement the Comparable interface, the moment you offer() the second student, Java will crash with a ClassCastException because it doesn't know how to compare them.
  • Using remove(Object) instead of poll(). While poll() removes the root in O(log N) time, searching for a specific object in the middle of a heap and removing it is an O(N) operation because heaps are not built for random searching.

Interview Questions

What is the time complexity of offer() and poll() in a Priority Queue?

Both offer() (insertion) and poll() (removal) run in O(log N) time. This is because adding or removing requires 'bubbling up' or 'sifting down' the tree to restore the heap property. Finding the minimum (peek()) is O(1).

How would you find the Kth largest element in an array of N elements?

Using a Min-Heap Priority Queue of size K. Iterate through the array, adding elements to the PQ. If the PQ size exceeds K, poll() the smallest element out. At the end of the array, the PQ holds the K largest elements, and the root (peek()) is exactly the Kth largest. This takes O(N log K) time, which is much faster than sorting the whole array O(N log N).

Real-World Example

Dijkstra's Algorithm for GPS navigation uses a Priority Queue. When exploring routes to a destination, the algorithm always wants to explore the 'currently known shortest path' next. A Priority Queue instantly provides the node with the lowest travel cost at every step.

example
java
PriorityQueue<RouteNode> pq = new PriorityQueue<>(
    (a, b) -> Integer.compare(a.costFromStart, b.costFromStart)
);

// Add the starting city
pq.offer(new RouteNode("New York", 0));

while (!pq.isEmpty()) {
    // O(1) to find, O(log N) to extract the cheapest path so far
    RouteNode cheapest = pq.poll(); 
    
    if (cheapest.city.equals(destination)) {
        return cheapest.costFromStart; // Found the shortest route!
    }
    
    // Explore neighbors...
}

Check Your Knowledge

Test your understanding of Priority Queue with these quick questions.

Question 1

By default, what type of element does Java's PriorityQueue return first?

Question 2

What is the time complexity of removing the highest priority element (`poll()`)?

Question 3

If you iterate over a PriorityQueue using a for-each loop, what order will the elements be in?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A