Data Structures & AlgorithmsVery hardProduct company OA

Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap counts)?

Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap counts)?
import heapq
h, swaps = [], 0
def push(x):
    global swaps
    h.append(x); i = len(h) - 1
    while i and h[(i - 1) // 2] > h[i]:
        h[(i - 1) // 2], h[i] = h[i], h[(i - 1) // 2]; i = (i - 1) // 2; swaps += 1
for x in [9, 8, 7, 6, 5, 4, 3]: push(x)
a = [9, 8, 7, 6, 5, 4, 3]; s2 = 0
def sift(i, n):
    global s2
    while 2 * i + 1 < n:
        c = 2 * i + 1
        if c + 1 < n and a[c + 1] < a[c]: c += 1
        if a[i] <= a[c]: break
        a[i], a[c] = a[c], a[i]; i = c; s2 += 1
for i in range(len(a) // 2 - 1, -1, -1): sift(i, len(a))
print(h, swaps, a, s2)
  1. A. [3, 6, 4, 9, 7, 8, 5] 10 [3, 6, 4, 9, 7, 8, 5] 10
  2. B. [3, 5, 4, 6, 8, 9, 7] 4 [3, 5, 4, 6, 8, 9, 7] 4
  3. C. [3, 6, 4, 9, 7, 8, 5] 10 [3, 5, 4, 6, 8, 9, 7] 4
  4. D. [3, 6, 4, 9, 7, 8, 5] 11 [3, 5, 4, 6, 8, 9, 7] 5

Correct answer: C. [3, 6, 4, 9, 7, 8, 5] 10 [3, 5, 4, 6, 8, 9, 7] 4

Each new (smaller) key climbs to the root: depths 0, 1, 1, 2, 2, 2, 2 → 10 swaps; in general reverse-sorted input costs Θ(n log n) this way. Heapify sifts down from the last internal node: 7 swaps with 3, 8 with 5, then 9 goes down twice (9↔3, then 9↔4) → 4 swaps, Θ(n) in general because most nodes are near the bottom. The two procedures build DIFFERENT valid heaps from the same input – both arrays satisfy the heap property.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic