A data structure for n elements and O(1) operations
Last Updated :
25 Mar, 2023
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.
Initialization:
We create an array of size n and initialize all elements as absent.
C++
void initialize(int n)
{
bool A[n];
for (int i = 0; i < n; i++)
A[i] = false;
}
|
C
void initialize(int n)
{
bool A[n];
for (int i = 0; i<n; i++)
A[i] = {0};
}
|
Java
void initialize(int n)
{
boolean A[n];
for (int i = 0; i<n; i++)
A[i] = false;
}
|
Python3
def initialize(n):
A = [False] * n
|
C#
void initialize(int n)
{
bool[] A = new bool[n];
for (int i = 0; i < n; i++)
A[i] = false;
}
|
Javascript
function initialize(n) {
let A = new Array(n);
for (let i = 0; i < n; i++) {
A[i] = false;
}
}
|
Insertion of an element:
C
void insert(unsigned i)
{
A[i] = 1;
}
|
C++
void insert(int i)
{
A[i] = true;
}
|
Java
void insert(int i)
{
A[i] = true;
}
|
Python3
def insert(i):
A[i] = True
|
C#
void insert(int i)
{
A[i] = true;
}
|
Javascript
void insert(unsigned i)
{
A[i] = true;
}
|
Deletion of an element:
C++
void delete(int i)
{
A[i] = false;
}
|
C
void delete(unsigned i)
{
A[i] = 0;
}
|
Java
void delete(int i)
{
A[i] = false;
}
|
Python3
def delete(i):
A[i] = False
|
C#
void delete(int i)
{
A[i] = false;
}
|
Javascript
function delete(i) {
A[i] = false;
}
|
Finding an element:
C++
bool Find(int i)
{
return A[i];
}
|
C
bool find(unsigned i)
{
return A[i];
}
|
Java
boolean find(int i)
{
return A[i];
}
|
C#
bool Find(int i)
{
return A[i];
}
|
Javascript
function find(i) {
return A[i] ? true : false;
}
|
Python3
As an exercise, change the data structure so that it holds values from 1 to n instead of 0 to n-1.
Please Login to comment...