Open In App

Data Structures | Misc | Question 5

A data structure is required for storing a set of integers such that each of the following operations can be done in (log n) time, where n is the number of elements in the set.

   o	Deletion of the smallest element 
   o	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

Answer: (B)
Explanation:

A self-balancing balancing binary search tree containing n items allows the lookup, insertion, and removal of an item in O(log n) worst-case time. Since it\’s a BST, we can easily find out minimum element in O(nlogn). See our post Find the minimum element in a Binary Search Tree for details. Since Heap is a balanced binary tree (or almost complete binary tree), insertion complexity for heap is O(logn). Also complexity to get minimum in a min heap is O(logn) because removal of root node causes a call to heapify (after removing the first element from the array) to maintain the heap tree property. But a heap cannot be used for the above purpose as the question says – insert an element if it is not already present. For a heap, we cannot find out in O(logn) if an element is present or not. Thanks to game for providing the correct solution.

Quiz of this Question
Please comment below if you find anything wrong in the above post

Article Tags :