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
- Check if an array is Wave Array
- Search, insert and delete in an unsorted array
- Print All Distinct Elements of a given integer array
- Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
- Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation
- Decode a given pattern in two ways (Flipkart Interview Question)
- Maximum Sum Path in Two Arrays
- Program to cyclically rotate an array by one
- Smallest subarray with sum greater than a given value
- Find the number of zeroes
- Rearrange positive and negative numbers in O(n) time and O(1) extra space
- Equilibrium index of an array
- k largest(or smallest) elements in an array | added Min Heap method
- Sort elements by frequency | Set 1