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?- A. [9, 6, 5, 3, 2, 4, 1]
- B. [9, 5, 6, 3, 2, 4, 1]
- C. [9, 5, 6, 1, 2, 4, 3]
- 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
- Problem: Insert keys into a hash table of size 7 with open addressing and LINEAR probing, h(k) = k mod 7. python T = [None] 7 for k in…
- Problem: Double hashing with h1(k) = k mod 11 and h2(k) = 7 − (k mod 7); probe i is (h1 + i·h2) mod 11. Print the slots probed for key 58…
- Problem: Exponential (galloping) search: double the bound until a[hi] ≥ target, then binary search in (hi/2, hi]. Count the comparisons of…
- Problem: Count unique quadruplets (as value multisets) summing to target with sort + two nested loops + two pointers. python def four(a…
- Problem: For each element, the nearest smaller value to its LEFT (−1 if none), with a monotonic stack. python def leftsmaller(a): st, out…
- Problem: Report the first negative number in every window of size k (0 if none), using a queue of negative indices. python from…