A data structure is required for storing a set of integers such that each of…
2021
A data structure is required for storing a set of integers such that each of the following operations can be done in \(O(log \ n)\) time, where \(n\) is the number of elements in the set.
Deletion of the smallest element
Insertion of an element if it is not already present in the set
Which of the following data structures can be used for this purpose?
- A.
A heap can be used but not a balanced binary search tree.
- B.
A balanced binary search tree can be used but not a heap.
- C.
Both balanced binary search tree and heap can be used.
- D.
Neither balanced binary search tree nor heap can be used.
Attempted by 341 students.
Show answer & explanation
Correct answer: B
Answer: A balanced binary search tree can be used but not a heap.
Reasoning:
Balanced binary search tree: search for an element in O(log n). To insert only if not present, perform the search in O(log n) and, if absent, insert in O(log n). Deleting the smallest element is done by finding the leftmost node (O(log n)) and deleting it (O(log n)).
Heap: extracting the minimum and inserting (unconditionally) are O(log n), but checking whether an element is already present in a plain heap requires O(n) in the worst case because the heap is not arranged for ordered search. Therefore a plain heap cannot guarantee insertion-if-not-present in O(log n).
Practical note: you can augment a heap with an auxiliary hash set to get O(1) membership checks and keep extract-min/insert costs O(log n), but that uses additional data structures. The simplest single data structure that meets both requirements is a balanced binary search tree.
A video solution is available for this question — log in and enroll to watch it.