- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
A data structure for n elements and O(1) operations?
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]; }
Advertisements