Algorithms

PriorityQueue / Heap

๐Ÿ“‹ Quick Reference

PropertyValue
TypeMin-heap by default (or max with comparator)
Insert (offer)O(log n)
Remove Min (poll)O(log n)
Peek MinO(1)
MemoryO(n) - array-backed
Best ForProcessing elements by priority, scheduling
One-liner: Binary heap providing O(log n) insert and O(1) access to smallest element.

๐ŸŽฎ Interactive Visualizer

Watch how the heap maintains its properties during insertions and extractions:

Loading visualizer...
Try these operations:
  1. Insert elements - see "bubble up" (heapify up)
  2. Poll minimum - watch "bubble down" (heapify down)
  3. Notice: parent โ‰ค children (min-heap property)
  4. Peek - instant O(1) access to root

๐Ÿ”ง Key Operations

Creating

JAVA(16 lines)
Code
Loading syntax highlighter...

Adding

JAVA(3 lines)
Code
Loading syntax highlighter...

Accessing

JAVA(2 lines)
Code
Loading syntax highlighter...

Removing

JAVA(4 lines)
Code
Loading syntax highlighter...

Other Operations

JAVA(4 lines)
Code
Loading syntax highlighter...

๐Ÿ“Š Complexity Analysis

OperationTimeNotes
offer(e)O(log n)Bubble up
poll()O(log n)Replace root + bubble down
peek()O(1)Just return root
remove(e)O(n)Linear search + O(log n) restructure
contains(e)O(n)Linear search
size()O(1)Stored field
heapify (constructor)O(n)Build heap from array

Heap Structure

Array representation of min-heap:
Index:    0   1   2   3   4   5   6
Value:   [1] [3] [2] [7] [4] [5] [6]

Tree view:
           1          <- root (index 0)
         /   \
        3     2       <- level 1 (indices 1, 2)
       / \   / \
      7   4 5   6     <- level 2 (indices 3-6)

Parent of i: (i-1)/2
Left child: 2*i + 1
Right child: 2*i + 2

โœ… When to Use PriorityQueue

Good Use Cases

  • Task scheduling - process highest priority first
  • K-smallest/largest - find top K elements
  • Dijkstra's algorithm - next closest vertex
  • Merge K sorted lists - next smallest element
  • Median finding - two heaps approach

Avoid When

  • Need all elements sorted - use TreeSet or sort array
  • Frequent contains() checks - O(n) each time
  • Need indexed access - no get(i) method
  • Need to remove arbitrary elements - O(n) to find

๐Ÿงฉ Common Patterns

Top K Elements

JAVA(14 lines)
Code
Loading syntax highlighter...

K Closest Points

JAVA(13 lines)
Code
Loading syntax highlighter...

Merge K Sorted Lists

JAVA(23 lines)
Code
Loading syntax highlighter...

โš ๏ธ Common Pitfalls

1. Assuming Sorted Iteration

JAVA(11 lines)
Code
Loading syntax highlighter...

2. Using contains() Frequently

JAVA(8 lines)
Code
Loading syntax highlighter...

3. Wrong Comparator for Max-Heap

JAVA(7 lines)
Code
Loading syntax highlighter...

4. Modifying Elements After Insert

JAVA(9 lines)
Code
Loading syntax highlighter...

๐ŸŽค Interview Tips

Q: How would you implement a max-heap in Java?
"
Use PriorityQueue with Comparator.reverseOrder() or a custom comparator that reverses the natural ordering. Example: new PriorityQueue<>(Collections.reverseOrder())
Q: How do you find the kth largest element?
"

Use a min-heap of size k. Add all elements; if size exceeds k, poll the minimum. After processing, the heap root is the kth largest. Time: O(n log k).

Q: Why is heapify O(n) instead of O(n log n)?
"

While each sift-down is O(log n), most nodes are near the leaves where sift-down is cheap. Mathematical analysis shows the sum converges to O(n), not O(n log n).

Q: PriorityQueue vs TreeSet?
"

PriorityQueue allows duplicates, is faster for just min/max operations, but iteration is unordered. TreeSet maintains sorted order, no duplicates, and supports range queries.


๐Ÿ“š Series Navigation


Visualizer: PriorityQueue from @tomaszjarosz/react-visualizers