00:00

Problem Statement

Input/Output Examples

Visual Explanation

The tree is always complete, so its height is log2 n, and each sift moves along one root-to-leaf path.

Approaches

The array heap gives logarithmic operations. The sorted list is a simple reference that trades fast extraction for slow insertion.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. The heap's insert and extract follow one path of length log n; peek is O(1). Building a heap from n values at once can be done in O(n).

Interview Tips and Recommended Approach

  • Know the index formulas: parent (i - 1) / 2, children 2i + 1 and 2i + 2.
  • Sift down towards the smaller child, or the heap property breaks.
  • Know heapify. Sifting down from the middle to the root builds a heap in linear time.
  • Know the uses: priority queues, heap sort, Dijkstra and top-k problems.

Recommended Approach: Array-Based Binary Heap

Why: it gives logarithmic insert and extract with a single array and no pointers, which is why the JDK uses the same design.