Open In App

ISRO | ISRO CS 2009 | Question 25

Last Updated : 04 Jun, 2018
Like Article
Like
Save
Share
Report

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.
I. Deletion of the smallest element
II. 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 search tree nor heap can be used


Answer: (B)

Explanation: A self-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 self balancing BST, we can easily find out minimum element in O(logn) time which is always the leftmost element.

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.

So, option (B) is correct.

Quiz of this Question


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads