- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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]; }

- Related Questions & Answers
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Dictionary Operations in Data Structure
- Count frequencies of all elements in array in O(1) extra space and O(n) time in C++
- Find median of BST in O(n) time and O(1) space in Python
- Find median of BST in O(n) time and O(1) space in C++
- Max WBLT Operations in Data Structure
- Rearrange positive and negative numbers in O(n) time and O(1) extra space in C++
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python
- Check for balanced parentheses in an expression O(1) space O(N^2) time complexity in Python
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Find duplicates in constant array with elements 0 to N-1 in O(1) space in C++
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Find the maximum repeating number in O(n) time and O(1) extra space in Python
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Find duplicate in an array in O(n) and by using O(1) extra space in C++

Advertisements