Open In App

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

Last Updated : 25 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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}; // or A[n] = {false};
}


Java




void initialize(int n)
{
  boolean A[n];
  for (int i = 0; i<n; i++)
    A[i] = false;
}
 
// This code is contributed by aadityaburujwale.


Python3




def initialize(n):
    A = [False] * n
 
# This code is contributed by akashish__


C#




void initialize(int n)
{
    bool[] A = new bool[n];
    for (int i = 0; i < n; i++)
        A[i] = false;
}
 
// This code is contributed by akashish__


Javascript




function initialize(n) {
  let A = new Array(n);
  for (let i = 0; i < n; i++) {
    A[i] = false;
  }
}
 
// This code is contributed by akashish__


Insertion of an element: 

C




void insert(unsigned i)
{
   /* set the value at index i to true */
   A[i] = 1; // Or A[i] = true;
}


C++




void insert(int i)
{
   /* set the value at index i to true */
   A[i] = true;
}


Java




void insert(int i)
{
   /* set the value at index i to true */
   A[i] = true;
}
 
// This code is contributed by aadityaburujwale.


Python3




def insert(i):
    """Set the value at index i to True."""
    A[i] = True
# This code is contributed by akashish__


C#




void insert(int i)
{
   /* set the value at index i to true */
   A[i] = true;
}
 
// This code is contributed by akashish__


Javascript




void insert(unsigned i)
{
   /* set the value at index i to true */
   A[i] = true;
}
// This code is contributed by akashish__


Deletion of an element: 

C++




void delete(int i)
{
    /* make the value at index i to false */
    A[i] = false;
}


C




void delete(unsigned i)
{
  /* make the value at index i to 0 */
  A[i] = 0;  // Or A[i] = false;
}


Java




void delete(int i)
{
  /* make the value at index i to false */
  A[i] =  false;
}
 
// This code is contributed by aadityaburujwale.


Python3




#Python equivalent of the code
def delete(i):
  """ make the value at index i to false """
  A[i] = False


C#




void delete(int i)
{
    /* make the value at index i to false */
    A[i] = false;
}
 
// This code is contributed by Akshay Tripathi(akshaytripathi19410)


Javascript




function delete(i) {
    // make the value at index i false
    A[i] = false;
}


Finding an element: 

C++




// Returns true if 'i' is present, else false
bool Find(int i)
{
    return A[i];
}


C




// Returns true if 'i' is present, else false
bool find(unsigned i)
{
    return A[i];
}


Java




// Returns true if 'i' is present, else false
boolean find(int i)
{
    return A[i];
}
 
// This code is contributed by aadityaburujwale.


C#




// Returns true if 'i' is present, else false
bool Find(int i)
{
    return A[i];
}


Javascript




// Returns true if 'i' is present, else false
// JavaScript
function find(i) {
    return A[i] ? true : false;
}
// This code is contributed by akashish__


Python3




# code
def Find(i):
  return A[i]


As an exercise, change the data structure so that it holds values from 1 to n instead of 0 to n-1.



Next Article
Article Tags :
Practice Tags :

Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Minimum operations to reduce array elements to zero using prefix operations and updates
Given an array arr[] of length N. We can apply 2 types of operations on element of arr[]: Choose a prefix let say arr[0, i] (0 <= i < N) and decrement all elements of prefix by 1. This operation can only apply if all elements in the prefix > 0. Choose an element arr[i] (0 <= i < N) and update it to 0.The task is to output the minimum
8 min read
Basic Operations for Queue in Data Structure
Basic Operations on Queue: Some of the basic operations for Queue in Data Structure are: enqueue() - Insertion of elements to the queue.dequeue() - Removal of elements from the queue.peek() or front()- Acquires the data element available at the front node of the queue without deleting it.rear() - This operation returns the element at the rear end w
11 min read
Design an efficient data structure for given operations
To design an efficient data structure for a specific set of operations, it's important to consider the time and space complexity of different data structures and choose the one that is best suited for the specific requirements. For example, if you need to perform operations such as inserting elements, finding the minimum element, and deleting the m
15+ min read
Basic Operations in Stack Data Structure with Implementations
In order to make manipulations in a stack, there are certain operations provided to us for Stack, which include: push() to insert an element into the stackpop() to remove an element from the stacktop() Returns the top element of the stack.isEmpty() returns true if the stack is empty else false.size() returns the size of the stack.In this post, we w
13 min read
Data Structure Alignment : How data is arranged and accessed in Computer Memory?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an address equal to some multiple of the word size.
4 min read
Difference between data type and data structure
Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compile
4 min read
Is array a Data Type or Data Structure?
What is Data Type? In computer programming, a data type is a classification of data that determines the type of values that can be stored, manipulated, and processed. It tells the computer what kind of data a particular variable or constant can hold, and what operations can be performed on that data. Common data types include integers, floating-poi
8 min read
Minimum operations required to Sort the Array using following operations
Given an array arr[] of size N. Make the array arr[] sorted in non-decreasing order in the minimum number of operations where you can choose any integer x and replace elements arr[i] == x equal to 0 for, 0 ? i ? N - 1. Examples: Input: n = 3, arr[] = {3, 3, 2}Output: 1Explanation: If you choose x = 3 then after one operation array will become {0, 0
10 min read
Count arrays having at least K elements exceeding XOR of all given array elements by X given operations
Given an array arr[] of size N, the task is to count the number of arrays having at least K elements greater than the XOR of all array elements, generated by performing the following operations X times. Select either first or last element from the given array.Either increment the selected element by 1 or delete the selected element. Examples: Input
10 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion and deletion operations are costly in the case of
5 min read
Applications, Advantages and Disadvantages of Hash Data Structure
Introduction : Imagine a giant library where every book is stored in a specific shelf, but instead of searching through endless rows of shelves, you have a magical map that tells you exactly which shelf your book is on. That's exactly what a Hash data structure does for your data! Hash data structures are a fundamental building block of computer sc
7 min read
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure
15+ min read
Data Structure for Dictionary and Spell Checker?
Which data structure can be used for efficiently building a word dictionary and Spell Checker? The answer depends upon the functionalists required in Spell Checker and availability of memory. For example following are few possibilities. Hashing is one simple option for this. We can put all words in a hash table. Refer this paper which compares hash
5 min read
Design a Data Structure that performs add in O(n) and getMinimum & deleteMinimum in O(1)
Design a data structure which can do following operations add() in O(n)getMinimum() in O(1)deleteMinimum() in O(1)Source : MakeMyTrip Interview. Maintain a linkedlist with elements in increasing order.Move head to next position in case of delete Min operation.Return First element in case of get Min Operation.Implementation: [GFGTABS] C++ #include
7 min read
Add and Search Word - Data Structure Design
Design a data structure GFGDictionary that enables to support the feature of adding new words and searching for words. The GFGDictionary class should have the following implementation: GFGDictionary(): constructor to initialize the objectvoid insertWord(word): function to insert word into the data structure.bool findWord(word): function to return t
4 min read
Maths for Data Structure and Algorithms (DSA) | A Complete Guide
Maths is a fundamental component of learning Data Structure and Algorithms, just like in programming. Maths is primarily used to evaluate the effectiveness of different algorithms. However, there are situations when the answer requires some mathematical understanding or the problem has mathematical characteristics and certain problems demand more t
15+ min read
Applications, Advantages and Disadvantages of Matrix Data Structure
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. For example, A matrix with 9 elements is shown below.  This Matrix [M] has 3 rows and 3 columns. Each element of matrix [M] can be referred to by its row and column number. For example
4 min read
Data Structure Types, Classifications and Applications
What is Data Structure:A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. A data structure is not only used for organizing the data. It is also used for processing, retrieving, and storing data. Different basic and advanced types of d
15+ min read
Design a data structure that supports insert, delete, search and getRandom in constant time
Design a data structure that supports the following operations in O(1) time. insert(x): Inserts an item x to the data structure if not already present.remove(x): Removes item x from the data structure if present. search(x): Searches an item x in the data structure.getRandom(): Returns a random element from the current set of elements We can use has
5 min read
Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
DSA has been one of the most popular go-to topics for any interview, be it college placements, software developer roles, or any other technical roles for freshers and experienced to land a decent job. If you are among them, you already know that it is not easy to find the best DSA interview questions among the vast pool of available problems. So he
4 min read
Matrix Data Structure Components, Applications, Advantages and Disadvantages
Matrix is a two-dimensional array or table consisting of rows and columns. The intersection of a row and column is called a cell. All the data is stored across different cells in the matrix. Matrix data structure is used when we want to store data in the form of table or grid. Each element in a matrix is identified by its row and column indices. Co
3 min read
Trie Data Structure | Insert and Search
The Trie data structure is a tree-like data structure used for storing a dynamic set of strings. It is commonly used for efficient retrieval and storage of keys in a large dataset. The structure supports operations such as insertion, search, and deletion of keys, making it a valuable tool in fields like computer science and information retrieval. I
15+ min read
Minimum Bitwise AND operations to make any two array elements equal
Given an array of integers of size 'n' and an integer 'k', We can perform the Bitwise AND operation between any array element and 'k' any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two elements of the array equal after performing
10 min read
Minimize absolute difference between the smallest and largest array elements by minimum increment decrement operations
Given an array arr[] consisting of N positive integers, the task is to minimize the number of operations required to minimize the absolute difference between the smallest and largest elements present in the array. In each operation, subtract 1 from an array element and increment 1 to another array element. Examples: Input: arr[] = {1, 6}Output: 2Ex
8 min read
Maximize difference between odd and even indexed array elements by shift operations
Given an array arr[] of size N, the task is to maximize the absolute difference between the sum of even indexed elements and the sum of odd indexed elements by left shift or right shift of array elements any number of times. Examples: Input: arr[] = {332, 421, 215, 584, 232}Output: 658Explanation: Convert the array to {233, 421, 152, 845, 223}, Sum
9 min read
Minimum number that can be obtained by applying '+' and '*' operations on array elements
Given an array arr[] consisting of N positive integers and a string S of length (N - 1), containing characters '+' and '*', the task is to find the smallest number that can be obtained after applying the arithmetic operations mentioned in the string S on the array elements in any order. Examples: Input: A[] ={2, 2, 2, 2}, S = "**+"Output: 8Explanat
11 min read
Minimize dissolve operations to make all elements 0 except first and last
Given an array arr of length N, the task is to find the minimum number of operations required to make all array elements 0, except first and last, using the given operation any number of times: In each operation choose 3 indices 1 ≤ i < j < k ≤ n, such that arr[j]>=2, andSubtract 2 from arr[j] and add 1 to both arr[i] and arr[k].Examples I
10 min read
Minimum steps to reach end from start by performing multiplication and mod operations with array elements
Given start, end and an array of N numbers. At each step, start is multiplied with any number in the array and then mod operation with 100000 is done to get the new start. The task is to find the minimum steps in which end can be achieved starting from start. Examples: Input: start = 3 end = 30 a[] = {2, 5, 7} Output: 2 Step 1: 3*2 = 6 % 100000 = 6
15+ min read
  翻译: