Propose a data structure for the following:
The data structure would hold elements from 0 to n-1. There is no order on the elements (no ascending/descending order requirement)
The complexity of the operations should be as follows:
* Insertion of an element – O(1)
* Deletion of an element – O(1)
* Finding an element – O(1)
We strongly recommend to minimize the browser and try this yourself first.
A boolean array works here. Array will have value ‘true’ at ith index if i is present, and ‘false’ if absent.
We create an array of size n and initialize all elements as absent.
Insertion of an element:
Deletion of an element:
Finding an element:
As an exercise, change the data structure so that it holds values from 1 to n instead of 0 to n-1.
This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Sort elements by frequency | Set 1
- k largest(or smallest) elements in an array | added Min Heap method
- Maximum sum such that no two elements are adjacent
- Two elements whose sum is closest to zero
- Find the smallest and second smallest elements in an array
- Maximum difference between two elements such that larger element appears after the smaller number
- Find the two repeating elements in a given array
- Check if array elements are consecutive | Added Method 3
- Count smaller elements on right side
- Find four elements that sum to a given value | Set 1 (n^3 solution)
- Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
- Sort elements by frequency | Set 2
- Given an array of of size n and a number k, find all elements that appear more than n/k times
- Find the element before which all the elements are smaller than it, and after which all are greater
- Remove minimum elements from either side such that 2*min becomes more than max