Codacoda
Back to Academy

trees

Binary Heap

A Binary Heap is a complete binary tree that satisfies the heap property: in a min-heap, every parent node is smaller than or equal to its children, and in a max-heap, every parent is greater than or equal to its children. It is typically implemented using an array for space efficiency. Binary heaps are the foundation of the heap sort algorithm and priority queues.

Use Cases

  • Priority queues for task scheduling
  • Heap sort algorithm implementation
  • Finding the k-th smallest or largest element efficiently

Complexity Analysis

MetricBestAverageWorst
TimeO(1)O(log n)O(log n)
SpaceO(n)

Visualization

3510255201530
35
10
25
5
20
15
30
Speed:1x
Initial arrayStep 1 / 6

Implementation

Output

Click "Run Code" to see output...