Question 31
MediumIn an array-based min-heap (0-indexed), where is the parent of the element at index i?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
In an array-based min-heap (0-indexed), where is the parent of the element at index i?
i // 2 + 1
2i + 1
i − 1
(i − 1) // 2
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
import heapq
a, k = [7, 10, 4, 3, 20, 15], 4
h = []
for x in a:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
print(h[0])
4
7
Sign up free to see the answer and a step-by-step explanation.
What is the time complexity of finding the k largest elements of n using a min-heap of size k?
O(n log n)
O(k log n)
O(n²)
O(n log k)
Sign up free to see the answer and a step-by-step explanation.
Which heap operation is used to remove the root?
Delete the root and leave a gap
Remove the last element
Rebuild the heap from scratch
Move the last element to the root and sift it down
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
import heapq
h = []
for x in [5, 3, 8, 1, 9, 2]:
heapq.heappush(h, x)
print(h[0], [heapq.heappop(h) for _ in range(3)])
1 [1, 3, 5]
1 [9, 8, 5]
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
import heapq
a = [7, 10, 4, 3, 20, 15]
k = 3
h = a[:k]
heapq.heapify(h)
for x in a[k:]:
if x > h[0]:
heapq.heapreplace(h, x)
print(h[0])
10
4
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
import heapq
lists = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
print(list(heapq.merge(*lists))[3:6])
[4, 7, 2]
[4, 5, 6]
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
import heapq
sticks = [2, 4, 3]
heapq.heapify(sticks)
cost = 0
while len(sticks) > 1:
a, b = heapq.heappop(sticks), heapq.heappop(sticks)
cost += a + b
heapq.heappush(sticks, a + b)
print(cost)
16
14
Sign up free to see the answer and a step-by-step explanation.
12 is inserted into the min-heap [10, 20, 15, 30, 40]. What is the array afterwards?
[10, 12, 15, 30, 40, 20]
[12, 10, 15, 30, 40, 20]
[10, 20, 15, 30, 40, 12]
[10, 20, 12, 30, 40, 15]
Sign up free to see the answer and a step-by-step explanation.
The minimum is removed from the min-heap [10, 20, 15, 30, 40]. What is the array afterwards?
[20, 15, 30, 40]
[15, 20, 30, 40]
[15, 20, 40, 30]
[15, 30, 20, 40]
Sign up free to see the answer and a step-by-step explanation.
10
20
1 [1, 2, 3]
5 [1, 2, 3]
7
15
[3, 4, 5]
[2, 5, 8]
9
12