Suggest a data structure which can optimize all 3 below operations :
Assume that you are putting integers/numbers.
Stack is a linear data structure in which the insertion and deletion operations are performed at only one end. In a stack, adding and removing of elements are performed at single position which is known as "top". That means, new element is added at top of the stack and an element is removed from the top of the stack.
Answer: 4 The type of data structure that allows insertion, as well as the deletion from both the ends, is the dequeue type of data structure.
Explanation: The answer is d. i.e., single ended queue. Queue has two ends in which one end is used for the insertion and another end is used for the deletion.
To answer your question, if time to delete is the most important perspective, the LinkedList should be chosen.
Dynamic Array + Hashmap = O(1) for all three operations
Append to the tail of Array O(1), and add a value-index pair to Hashmap O(1).
Find the index by the value in Hashmap O(1), delete by the index in array and swap the last element into the slot O(1), and update the value-index pair for the (used-to-be) last element O(1).
Generate a random index for the array O(1).
O(1) in python:
from collections import defaultdict
from random import choice
class DataStructure(list):
def __init__(self):
self.values = []
self.locations = defaultdict(list)
def add(self, val):
i = len(self.values)
self.locations[val].append(i)
self.values.append(val)
assert self.values[i] == val
def delete(self, val):
locations = self.locations[val]
if locations:
i = locations.pop()
self.values[i] = self.values[-1]
self.values.pop()
def random(self):
return choice(self.values)
ds = DataStructure()
ds.add(3)
ds.add(5)
print ds.random()
print ds.random()
print ds.random()
print ds.random()
ds.delete(5)
print ds.random()
ds.delete(3)
"""
5
3
3
5
3
"""
See Time Complexities of List and Dict operations to Confirm
( Note pop is O(1) since we pop from the end of the list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With