Build heap from a given Array
Pattern: Heap implementation
Every leaf is already a heap. Walk the non-leaves from index n/2 - 1 back to 0 and sift each one down; when you reach a node, both its subtrees are heaps, so one sift makes its subtree a heap too. The total work is O(n).
The problem
Turn an array into a min heap in place. [6, 5, 2, 7, 1, 7] can become [1, 5, 2, 7, 6, 7]. The function returns
nothing.
Many arrays are valid answers, so the tests check that your result is a heap holding the same values.
Think first
- Which nodes are heaps already, with no work?
- If both children of a node are heap roots, what fixes the node?
- In which order must you visit the nodes?
Hints
Brute force, and why it fails
Insert the values one by one into an empty heap: O(n log n).
The key insight
Sifting down from the bottom up means most nodes, which sit near the leaves, move only a step or two, so the total is O(n), not O(n log n).
Dry run
nums = [6, 5, 2, 7, 1, 7], n = 6. Indexes 3, 4, 5 are leaves. Start at index 2: 2 is smaller than its child 7, fine.
The plan
for i from n / 2 - 1 down to 0:
siftDown(nums, i)
Complexity
- Time
O(n)- Space
O(1)
A node at height h sinks at most h levels, and about n / 2^(h+1) nodes have height h; the sum is below 2n.
Edge cases
- One value.
- Already a heap: nothing moves.
- Sorted descending: many swaps, still O(n).
I've built my logic, show the code
Java
class Solution {
public void buildMinHeap(int[] nums) {
for (int i = nums.length / 2 - 1; i >= 0; i--) siftDown(nums, i); // leaves are already heaps
}
private void siftDown(int[] a, int i) {
int n = a.length;
while (true) {
int l = 2 * i + 1, r = l + 1, small = i;
if (l < n && a[l] < a[small]) small = l;
if (r < n && a[r] < a[small]) small = r;
if (small == i) return;
int t = a[small]; a[small] = a[i]; a[i] = t;
i = small;
}
}
}C++
class Solution {
public:
void buildMinHeap(vector<int>& nums) {
for (int i = static_cast<int>(nums.size()) / 2 - 1; i >= 0; i--) siftDown(nums, i); // leaves are already heaps
}
void siftDown(vector<int>& a, int i) {
int n = static_cast<int>(a.size());
while (true) {
int l = 2 * i + 1, r = l + 1, small = i;
if (l < n && a[l] < a[small]) small = l;
if (r < n && a[r] < a[small]) small = r;
if (small == i) return;
swap(a[small], a[i]);
i = small;
}
}
};Python
class Solution:
def buildMinHeap(self, nums: list[int]) -> None:
for i in range(len(nums) // 2 - 1, -1, -1): # leaves are already heaps
self.sift_down(nums, i)
def sift_down(self, a: list[int], i: int) -> None:
n = len(a)
while True:
l, r, small = 2 * i + 1, 2 * i + 2, i
if l < n and a[l] < a[small]:
small = l
if r < n and a[r] < a[small]:
small = r
if small == i:
return
a[small], a[i] = a[i], a[small]
i = smallCommon mistakes
- Starting from index 0, so children are not heaps yet.
- Sifting up instead of down, which needs a different order and is O(n log n).