Heapify Algorithm
Pattern: Heap implementation
Set nums[ind] = val. If the value went down, it may be smaller than its parent: sift it up. If it went up, it may be bigger than a child: sift it down towards the smaller child. Only one of the two can move it, and each walks one path: O(log n).
The problem
nums is a min heap stored in an array. Set nums[ind] = val and restore the min-heap order in place. [1, 4, 5, 5, 7, 6] with ind = 5, val = 2 becomes [1, 4, 2, 5, 7, 5]. The function returns nothing; the tests print the array.
When a node has two equal children smaller than it, this guide swaps with the left one.
Think first
- After the change, which neighbours might now be out of order?
- If the value got smaller, which way can it need to move?
- And if it got bigger?
Hints
Brute force, and why it fails
Rebuild the whole heap from the changed array: O(n).
The key insight
A single changed value only breaks the order along one root-to-leaf path through it, so one sift (up or down) repairs it in O(log n).
Dry run
nums = [1, 4, 5, 5, 7, 6], ind = 5, val = 2. Write 2 at index 5.
The plan
nums[ind] = val
if val < old: while ind > 0 and nums[parent] > nums[ind]: swap; ind = parent
else: while a child is smaller: swap with the smaller child; move down
Complexity
- Time
O(log n)- Space
O(1)
The sift moves at most the height of the tree, which is about log n.
Edge cases
- The same value as before: nothing moves.
- Changing the root to a huge value: it sinks to a leaf.
- Changing a leaf to a tiny value: it rises to the root.
I've built my logic, show the code
Java
class Solution {
public void heapify(int[] nums, int ind, int val) {
int old = nums[ind];
nums[ind] = val;
if (val < old) siftUp(nums, ind); // smaller: it may need to rise
else siftDown(nums, ind); // larger: it may need to sink
}
private void siftUp(int[] a, int i) {
while (i > 0 && a[(i - 1) / 2] > a[i]) {
int p = (i - 1) / 2;
int t = a[p]; a[p] = a[i]; a[i] = t;
i = p;
}
}
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; // both children are at least as big
int t = a[small]; a[small] = a[i]; a[i] = t;
i = small;
}
}
}C++
class Solution {
public:
void heapify(vector<int>& nums, int ind, int val) {
int old = nums[ind];
nums[ind] = val;
if (val < old) siftUp(nums, ind); // smaller: it may need to rise
else siftDown(nums, ind); // larger: it may need to sink
}
void siftUp(vector<int>& a, int i) {
while (i > 0 && a[(i - 1) / 2] > a[i]) {
swap(a[(i - 1) / 2], a[i]);
i = (i - 1) / 2;
}
}
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; // both children are at least as big
swap(a[small], a[i]);
i = small;
}
}
};Python
class Solution:
def heapify(self, nums: list[int], ind: int, val: int) -> None:
old = nums[ind]
nums[ind] = val
if val < old:
self.sift_up(nums, ind) # smaller: it may need to rise
else:
self.sift_down(nums, ind) # larger: it may need to sink
def sift_up(self, a: list[int], i: int) -> None:
while i > 0 and a[(i - 1) // 2] > a[i]:
p = (i - 1) // 2
a[p], a[i] = a[i], a[p]
i = p
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 # both children are at least as big
a[small], a[i] = a[i], a[small]
i = smallCommon mistakes
- Sifting down towards the larger child, which breaks the order with the other child.
- Running both sifts in the wrong order; one is enough when you test which way the value moved.