Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview : Suggest a data structure which optimizes insertion, deletion and random value generation

Suggest a data structure which can optimize all 3 below operations :

  1. Insertion
  2. Deletion
  3. Return a random value from set of existing values

Assume that you are putting integers/numbers.

like image 384
rai.skumar Avatar asked Dec 26 '12 05:12

rai.skumar


People also ask

In which data structure do the insertion and deletion?

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.

Which of the following data structure allows insertion and deletion from both in?

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.

Which data structure is best for insertion and deletion in Java?

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.

Which data structure is best for deletion?

To answer your question, if time to delete is the most important perspective, the LinkedList should be chosen.


2 Answers

Dynamic Array + Hashmap = O(1) for all three operations

  • Insertion

Append to the tail of Array O(1), and add a value-index pair to Hashmap O(1).

  • Deletion

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).

  • Return random

Generate a random index for the array O(1).

like image 75
Dante May Code Avatar answered Nov 15 '22 10:11

Dante May Code


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)

like image 20
robert king Avatar answered Nov 15 '22 08:11

robert king