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

**(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

## Recommended Posts:

- Data Structures | Misc | Question 8
- Data Structures | Misc | Question 7
- Data Structures | Misc | Question 4
- Data Structures | Misc | Question 1
- Data Structures | Misc | Question 2
- Data Structures | Misc | Question 3
- Data Structures | Misc | Question 10
- Data Structures | Misc | Question 9
- Data Structures | Misc | Question 6
- Introduction to Data Structures | 10 most commonly used Data Structures
- Data Structures | B and B+ Trees | Question 2
- Data Structures | Hash | Question 1
- Data Structures | B and B+ Trees | Question 3
- Data Structures | Stack | Question 4
- Data Structures | Hash | Question 5