A data structure for n elements and O(1) operations?

CServer Side ProgrammingProgramming

Here we will see one data-structure with n elements, and O(1) operations. So the operations will take constant amount of time to execute.

The data structure will hold n elements (from 0 to n-1). The data can be in any order. The Insertion, deletion and searching will take O(1) amount of time.

To solve this problem, we will use one Boolean array. This will indicate that the item is present or not at position i. If the item is present, it will hold 1, otherwise 0.

Algorithm

initialization(n)

begin
   fill all elements of the Boolean array as 0
end

insert(i)

begin
   set element at index i as 1(true)
end

delete(i)

begin
set element at index i as 0(false)
end

search(i)

begin
   return item at position i
end

Example

//initialization
void init(int n) {
   bool dataStructure[n];
   for (int i = 0; i<n; i++)
      dataStructure[i] = 0;
}
//Insertion
void insert(unsigned i) {
   dataStructure[i] = 1;
}
//Deletion
void delete(unsigned i) {
   dataStructure[i] = 0;
}
//Search
bool search(unsigned i) {
   return dataStructure[i];
}
raja
Published on 24-Jul-2019 12:13:23
Advertisements