A data structure is required for storing a set of integers such that each of…

2003

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	Delection 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?

  1. A.

    A heap can be used but not a balanced binary search tree

  2. B.

    A balanced binary search tree can be used but not a heap

  3. C.

    Both balanced binary search tree and heap can be used

  4. D.

    Neither balanced binary search tree nor heap can be used

Attempted by 230 students.

Show answer & explanation

Correct answer: B

Answer: A balanced binary search tree (for example, an AVL tree or a red–black tree) can be used; a plain heap alone cannot.

Reasoning:

  • Balanced binary search tree: search, insertion and deletion all take O(log n) time when the tree is height-balanced. Deleting the smallest element is done by following left-child pointers to the leftmost node (O(log n)) and removing it (O(log n)). To insert only if not already present, first perform a search (O(log n)); if not found, insert (O(log n)). Hence both required operations run in O(log n).

  • Heap (min-heap): delete-min and insertion are O(log n). However, checking whether an element is already present in a plain heap requires scanning elements in the worst case, which is O(n). Therefore a plain heap cannot guarantee the "insert only if not already present" operation in O(log n).

  • Note: If you combine a heap with an auxiliary structure (for example, a hash table or an index map) you can get fast membership checks, but that uses multiple data structures. The question asks for a single data structure that supports both operations in O(log n), so a balanced BST is the appropriate choice.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir