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)- A. [3, 6, 4, 9, 7, 8, 5] 10 [3, 6, 4, 9, 7, 8, 5] 10
- B. [3, 5, 4, 6, 8, 9, 7] 4 [3, 5, 4, 6, 8, 9, 7] 4
- C. [3, 6, 4, 9, 7, 8, 5] 10 [3, 5, 4, 6, 8, 9, 7] 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed? python c = 0 n = 30 for i in…
- A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made? python…
- Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is…
- Weighted interval scheduling (start, end, value): DP over jobs sorted by end time with binary search for the last compatible job, versus…
- Broken-profile DP: number of ways to tile a 3 × n board with 1 × 2 dominoes, column by column with a 3-bit mask of cells already covered…
- Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is…