1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Max Heap
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
12Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Max Heap

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
11Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • 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

Max-Heap

Overview

A Max-Heap is the exact opposite of a Min-Heap. It is a Complete Binary Tree where every parent node is greater than or equal to its children. Therefore, the absolute largest element is always sitting instantly accessible at the root node.

Java's PriorityQueue is a Min-Heap by default. To create a Max-Heap in Java, you must provide a custom Comparator that reverses the natural sorting order (Collections.reverseOrder()).

Max-Heaps are crucial when you continuously need access to the highest-value item, such as processing the most critical bug in an issue tracker, or selecting the highest paying bid in an auction system.

Syntax

Max-Heap using Java's PriorityQueue
java
import java.util.PriorityQueue;
import java.util.Collections;

public class MaxHeapDemo {
    public static void main(String[] args) {
        // Reverse the natural integer ordering to create a Max-Heap
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
        
        maxHeap.offer(10);
        maxHeap.offer(99);
        maxHeap.offer(5);
        maxHeap.offer(42);
        
        // The largest element is immediately available
        System.out.println("Maximum: " + maxHeap.peek()); // 99
        
        // Extracting elements in descending order
        while (!maxHeap.isEmpty()) {
            System.out.println("Extracted: " + maxHeap.poll());
        }
        // Output: 99, 42, 10, 5
    }
}

Common Pitfalls

  • Forgetting the Collections.reverseOrder() argument. If you omit it, you will accidentally build a Min-Heap. This is the #1 mistake when writing Max-Heap logic in interviews.
  • Custom Object Comparators. When building a Max-Heap for custom objects (e.g., PriorityQueue<Student>), your comparator must be (a, b) -> b.score - a.score. Reversing the a and b in the subtraction reverses the sorting logic to descending order.
  • Integer Overflow in Custom Comparators. Using subtraction b.score - a.score is dangerous if the numbers are massive (can cause underflow/overflow errors). Always use Integer.compare(b.score, a.score) for safety.

Interview Questions

How do you find the Kth Smallest Element using a Max-Heap?

This sounds counter-intuitive! You use a Max-Heap of size K. Iterate through the array, pushing elements into the Max-Heap. If the heap size exceeds K, poll() (remove) the maximum element. Because you constantly throw away the largest elements, at the end of the array, the heap contains only the K smallest elements, and the root is the Kth smallest. Time: O(N log K).

What is HeapSort?

HeapSort is an O(N log N) sorting algorithm. You insert all elements into a Max-Heap. Then, you repeatedly extract the maximum element and place it at the end of the array, working backwards. It is extremely memory efficient (O(1) auxiliary space) but generally slower in practice than QuickSort due to poor cache locality.

Real-World Example

A Hospital Emergency Room Triage system uses a Max-Heap. Patients are assigned a severity score from 1 (minor) to 10 (life-threatening). The doctors always need to treat the patient with the highest severity score first, regardless of when they arrived.

example
java
class Patient {
    String name;
    int severity; // 1 to 10
    // constructor...
}

// Max-Heap: Compare p2 to p1 to reverse natural order
PriorityQueue<Patient> triage = new PriorityQueue<>(
    (p1, p2) -> Integer.compare(p2.severity, p1.severity)
);

triage.offer(new Patient("Alice", 2));
triage.offer(new Patient("Bob", 9));
triage.offer(new Patient("Charlie", 5));

// Bob is treated first because 9 is the maximum severity
Patient nextToTreat = triage.poll();

Check Your Knowledge

Test your understanding of Max-Heap with these quick questions.

Question 1

How do you instantiate a Max-Heap of Integers in Java?

Question 2

What is the time complexity of building a heap from an unsorted array of N elements using the optimal 'Heapify' process?

Question 3

To find the Kth *Smallest* element in an array optimally, you should use:

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

Max-Heap

Overview

A Max-Heap is the exact opposite of a Min-Heap. It is a Complete Binary Tree where every parent node is greater than or equal to its children. Therefore, the absolute largest element is always sitting instantly accessible at the root node.

Java's PriorityQueue is a Min-Heap by default. To create a Max-Heap in Java, you must provide a custom Comparator that reverses the natural sorting order (Collections.reverseOrder()).

Max-Heaps are crucial when you continuously need access to the highest-value item, such as processing the most critical bug in an issue tracker, or selecting the highest paying bid in an auction system.

Syntax

Max-Heap using Java's PriorityQueue
java
import java.util.PriorityQueue;
import java.util.Collections;

public class MaxHeapDemo {
    public static void main(String[] args) {
        // Reverse the natural integer ordering to create a Max-Heap
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
        
        maxHeap.offer(10);
        maxHeap.offer(99);
        maxHeap.offer(5);
        maxHeap.offer(42);
        
        // The largest element is immediately available
        System.out.println("Maximum: " + maxHeap.peek()); // 99
        
        // Extracting elements in descending order
        while (!maxHeap.isEmpty()) {
            System.out.println("Extracted: " + maxHeap.poll());
        }
        // Output: 99, 42, 10, 5
    }
}

Common Pitfalls

  • Forgetting the Collections.reverseOrder() argument. If you omit it, you will accidentally build a Min-Heap. This is the #1 mistake when writing Max-Heap logic in interviews.
  • Custom Object Comparators. When building a Max-Heap for custom objects (e.g., PriorityQueue<Student>), your comparator must be (a, b) -> b.score - a.score. Reversing the a and b in the subtraction reverses the sorting logic to descending order.
  • Integer Overflow in Custom Comparators. Using subtraction b.score - a.score is dangerous if the numbers are massive (can cause underflow/overflow errors). Always use Integer.compare(b.score, a.score) for safety.

Interview Questions

How do you find the Kth Smallest Element using a Max-Heap?

This sounds counter-intuitive! You use a Max-Heap of size K. Iterate through the array, pushing elements into the Max-Heap. If the heap size exceeds K, poll() (remove) the maximum element. Because you constantly throw away the largest elements, at the end of the array, the heap contains only the K smallest elements, and the root is the Kth smallest. Time: O(N log K).

What is HeapSort?

HeapSort is an O(N log N) sorting algorithm. You insert all elements into a Max-Heap. Then, you repeatedly extract the maximum element and place it at the end of the array, working backwards. It is extremely memory efficient (O(1) auxiliary space) but generally slower in practice than QuickSort due to poor cache locality.

Real-World Example

A Hospital Emergency Room Triage system uses a Max-Heap. Patients are assigned a severity score from 1 (minor) to 10 (life-threatening). The doctors always need to treat the patient with the highest severity score first, regardless of when they arrived.

example
java
class Patient {
    String name;
    int severity; // 1 to 10
    // constructor...
}

// Max-Heap: Compare p2 to p1 to reverse natural order
PriorityQueue<Patient> triage = new PriorityQueue<>(
    (p1, p2) -> Integer.compare(p2.severity, p1.severity)
);

triage.offer(new Patient("Alice", 2));
triage.offer(new Patient("Bob", 9));
triage.offer(new Patient("Charlie", 5));

// Bob is treated first because 9 is the maximum severity
Patient nextToTreat = triage.poll();

Check Your Knowledge

Test your understanding of Max-Heap with these quick questions.

Question 1

How do you instantiate a Max-Heap of Integers in Java?

Question 2

What is the time complexity of building a heap from an unsorted array of N elements using the optimal 'Heapify' process?

Question 3

To find the Kth *Smallest* element in an array optimally, you should use:

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