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

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
06Hrs
17Mins
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

Min-Heap

Overview

A Min-Heap is a specialized Complete Binary Tree where every parent node is smaller than or equal to its children. Consequently, the absolute smallest element in the entire structure is always at the root node.

While conceptually a tree, Heaps are almost always implemented using a flat Array to save memory (no pointers needed!). The parent-child relationships are calculated using simple math: for a node at index i, its left child is at 2i + 1 and its right child is at 2i + 2.

Min-Heaps are the underlying engine of the PriorityQueue. They allow you to add new elements in O(log N) time, and extract the minimum element in O(log N) time. They are the backbone of algorithms like Dijkstra's Shortest Path and Prim's Minimum Spanning Tree.

Syntax

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

public class HeapDemo {
    public static void main(String[] args) {
        // By default, Java's PriorityQueue is a Min-Heap
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        
        // Inserting elements (O(log N))
        // Internally, it adds to the end of the array and "bubbles up"
        minHeap.offer(45);
        minHeap.offer(10);
        minHeap.offer(25);
        minHeap.offer(5);
        
        // Peek views the minimum element without removing it (O(1))
        System.out.println("Current Minimum: " + minHeap.peek()); // 5
        
        // Extracting elements (O(log N))
        // Internally, it removes the root, moves the last element to the root, 
        // and "sifts down" to restore the heap property
        while (!minHeap.isEmpty()) {
            System.out.println("Extracting: " + minHeap.poll());
        }
        // Output: 5, 10, 25, 45 (Sorted!)
    }
}

Common Pitfalls

  • Iterating over a PriorityQueue expecting sorted order. for(int x : minHeap) iterates over the underlying array structure. A heap only guarantees the root is the minimum, it does NOT guarantee the whole array is strictly sorted. You must poll() to get sorted output.
  • Attempting to search for an arbitrary element. Heaps are designed for O(1) access to the root. Finding an element that isn't the root requires scanning the entire array, which is O(N). If you need fast searches, use a TreeSet instead.
  • Modifying objects inside the heap. If you add an object to a PriorityQueue and then change a property that affects its priority comparison, the heap will NOT automatically restructure. It will become corrupted. You must remove the object, update it, and re-add it.

Interview Questions

How is a Min-Heap represented as an Array?

It uses level-order traversal. The root is at index 0. For any node at index i: its left child is at 2i + 1, its right child is at 2i + 2, and its parent is at (i - 1) / 2.

Explain the 'Bubble Up' (or Heapify Up) process when inserting a new element.

When a new element is inserted, it is placed at the very end of the internal array to maintain the 'Complete Tree' property. Then, we compare it with its parent. If it is smaller than its parent, they swap. We repeat this 'bubbling up' process until it reaches a parent that is smaller, or it becomes the new root.

Real-World Example

Operating Systems use Min-Heaps for Timer and Event Scheduling. If you have 1,000 background tasks scheduled to run at specific future times, the OS places them in a Min-Heap ordered by execution time. The task that needs to run soonest is always at the root, allowing the OS scheduler to sleep until that exact millisecond.

example
java
class Task implements Comparable<Task> {
    String name;
    long executionTimeMs;
    
    public int compareTo(Task other) {
        return Long.compare(this.executionTimeMs, other.executionTimeMs);
    }
}

PriorityQueue<Task> taskScheduler = new PriorityQueue<>();
taskScheduler.offer(new Task("System Update", System.currentTimeMillis() + 60000));
taskScheduler.offer(new Task("Clear Cache", System.currentTimeMillis() + 5000));

// The scheduler simply checks the root to know when to wake up next
Task nextTask = taskScheduler.peek();
Thread.sleep(nextTask.executionTimeMs - System.currentTimeMillis());

Check Your Knowledge

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

Question 1

What property must a Binary Tree have to be considered a valid Heap?

Question 2

What is the formula to find the left child of a node at index `i` in an array-based Heap?

Question 3

What is the time complexity of extracting the minimum element (`poll()`) from a Min-Heap?

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

Min-Heap

Overview

A Min-Heap is a specialized Complete Binary Tree where every parent node is smaller than or equal to its children. Consequently, the absolute smallest element in the entire structure is always at the root node.

While conceptually a tree, Heaps are almost always implemented using a flat Array to save memory (no pointers needed!). The parent-child relationships are calculated using simple math: for a node at index i, its left child is at 2i + 1 and its right child is at 2i + 2.

Min-Heaps are the underlying engine of the PriorityQueue. They allow you to add new elements in O(log N) time, and extract the minimum element in O(log N) time. They are the backbone of algorithms like Dijkstra's Shortest Path and Prim's Minimum Spanning Tree.

Syntax

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

public class HeapDemo {
    public static void main(String[] args) {
        // By default, Java's PriorityQueue is a Min-Heap
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        
        // Inserting elements (O(log N))
        // Internally, it adds to the end of the array and "bubbles up"
        minHeap.offer(45);
        minHeap.offer(10);
        minHeap.offer(25);
        minHeap.offer(5);
        
        // Peek views the minimum element without removing it (O(1))
        System.out.println("Current Minimum: " + minHeap.peek()); // 5
        
        // Extracting elements (O(log N))
        // Internally, it removes the root, moves the last element to the root, 
        // and "sifts down" to restore the heap property
        while (!minHeap.isEmpty()) {
            System.out.println("Extracting: " + minHeap.poll());
        }
        // Output: 5, 10, 25, 45 (Sorted!)
    }
}

Common Pitfalls

  • Iterating over a PriorityQueue expecting sorted order. for(int x : minHeap) iterates over the underlying array structure. A heap only guarantees the root is the minimum, it does NOT guarantee the whole array is strictly sorted. You must poll() to get sorted output.
  • Attempting to search for an arbitrary element. Heaps are designed for O(1) access to the root. Finding an element that isn't the root requires scanning the entire array, which is O(N). If you need fast searches, use a TreeSet instead.
  • Modifying objects inside the heap. If you add an object to a PriorityQueue and then change a property that affects its priority comparison, the heap will NOT automatically restructure. It will become corrupted. You must remove the object, update it, and re-add it.

Interview Questions

How is a Min-Heap represented as an Array?

It uses level-order traversal. The root is at index 0. For any node at index i: its left child is at 2i + 1, its right child is at 2i + 2, and its parent is at (i - 1) / 2.

Explain the 'Bubble Up' (or Heapify Up) process when inserting a new element.

When a new element is inserted, it is placed at the very end of the internal array to maintain the 'Complete Tree' property. Then, we compare it with its parent. If it is smaller than its parent, they swap. We repeat this 'bubbling up' process until it reaches a parent that is smaller, or it becomes the new root.

Real-World Example

Operating Systems use Min-Heaps for Timer and Event Scheduling. If you have 1,000 background tasks scheduled to run at specific future times, the OS places them in a Min-Heap ordered by execution time. The task that needs to run soonest is always at the root, allowing the OS scheduler to sleep until that exact millisecond.

example
java
class Task implements Comparable<Task> {
    String name;
    long executionTimeMs;
    
    public int compareTo(Task other) {
        return Long.compare(this.executionTimeMs, other.executionTimeMs);
    }
}

PriorityQueue<Task> taskScheduler = new PriorityQueue<>();
taskScheduler.offer(new Task("System Update", System.currentTimeMillis() + 60000));
taskScheduler.offer(new Task("Clear Cache", System.currentTimeMillis() + 5000));

// The scheduler simply checks the root to know when to wake up next
Task nextTask = taskScheduler.peek();
Thread.sleep(nextTask.executionTimeMs - System.currentTimeMillis());

Check Your Knowledge

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

Question 1

What property must a Binary Tree have to be considered a valid Heap?

Question 2

What is the formula to find the left child of a node at index `i` in an array-based Heap?

Question 3

What is the time complexity of extracting the minimum element (`poll()`) from a Min-Heap?

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