Question 1
EasyIn a max-heap, where is the largest element?
- 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 a max-heap, where is the largest element?
At the last position
Anywhere
At the root
At a leaf
Answer: C
Every parent is ≥ its children, so the maximum is at the top.
What is the time complexity of inserting into a binary heap?
O(log n)
O(n)
O(n log n)
O(1)
Answer: A
The new element is added at the end and bubbles up at most the height of the tree.
Which data structure is usually used to implement a priority queue?
Linked list only
Hash table
Stack
Binary heap
Answer: D
Heaps give O(log n) insert and extract-min/max and O(1) peek.
What is the output of this code?
import heapq
h = [5, 3, 8, 1]
heapq.heapify(h)
print(h[0])
3
8
Answer: C
heapq maintains a min-heap, so heap[0] is the smallest element.
What is the time complexity of finding (peeking at) the minimum in a min-heap?
O(log n)
O(n log n)
O(n)
O(1)
Answer: D
In a min-heap every parent is ≤ its children, so the minimum is always the root, read in O(1).
Is a binary heap a complete binary tree?
Yes
Only when it has an odd number of nodes
No
Only a max-heap
Answer: A
Completeness lets the heap be stored in an array with no gaps.
What is the output of this code?
import heapq
h = []
for x in [3, 1, 2]:
heapq.heappush(h, x)
print([heapq.heappop(h) for _ in range(3)])
[2, 1, 3]
[3, 2, 1]
Answer: C
Popping from a min-heap returns elements in increasing order.
What is the heap property of a min-heap?
Every parent is greater than its children
Every parent is less than or equal to its children
All leaves are equal
The array is fully sorted
Answer: B
So the smallest element is always at the root.
Is the array [10, 20, 15, 30, 40] a valid min-heap (index 0 is the root)?
Only as a max-heap
Only if it is sorted
No
Yes
Answer: D
10 ≤ 20 and 10 ≤ 15; 20 ≤ 30 and 20 ≤ 40. Every parent is smaller than its children.
Is the array [10, 5, 15] a valid min-heap (index 0 is the root)?
It can't be decided
No, because 5 is smaller than its parent 10
Yes, it is a max-heap
Yes
Answer: B
In a min-heap a child must not be smaller than its parent.
1
5
[1, 2, 3]
[1, 3, 2]