Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Bottom-up heapify (max-heap) of an array; print the resulting array.

Problem: Bottom-up heapify (max-heap) of an array; print the resulting array.
def heapify(a):
    n = len(a)
    def down(i):
        while True:
            l, r, big = 2*i + 1, 2*i + 2, i
            if l < n and a[l] > a[big]: big = l
            if r < n and a[r] > a[big]: big = r
            if big == i: return
            a[i], a[big] = a[big], a[i]; i = big
    for i in range(n // 2 - 1, -1, -1): down(i)
    return a
print(heapify([3, 1, 6, 5, 2, 4, 9]))
What is printed?
  1. A. [9, 6, 5, 3, 2, 4, 1]
  2. B. [9, 5, 6, 3, 2, 4, 1]
  3. C. [9, 5, 6, 1, 2, 4, 3]
  4. D. [1, 2, 3, 4, 5, 6, 9]

Correct answer: C. [9, 5, 6, 1, 2, 4, 3]

Sift down from index 2 (6 vs 4, 9 → swap with 9), index 1 (1 vs 5, 2 → swap with 5), then index 0 (3 vs 5, 9 → swap with 9, then 3 vs 4, 6 → swap with 6): [9, 5, 6, 1, 2, 4, 3]. Bottom-up heapify is O(n) and does not sort the array.

More Coding Interview Problems questions

Exams that ask this topic