Insert Delete GetRandom O(1)

Problem: Insert Delete GetRandom O(1)

To implement O(1) delete, we can maintain a map which stores number and its index in the array. Everytime we want to remove an element, we can find it easily, swap it with the last one (also swap the index stored in the map) and remove it.

Code in Python:

import random

class RandomizedSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.m = {}
        self.l = []
        self.i = 0


    def insert(self, val):
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if val not in self.m:
            self.m[val] = self.i
            self.l.append(val)
            self.i += 1
            return True
        return False


    def remove(self, val):
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val in self.m:
            last = self.l[-1]
            index = self.m[val]
            self.l[-1], self.l[index] = self.l[index], self.l[-1]
            self.m[last] = index
            self.l.pop()
            del self.m[val]
            self.i -= 1
            return True
        return False


    def getRandom(self):
        """
        Get a random element from the set.
        :rtype: int
        """
        return random.choice(self.l)


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

results matching ""

    No results matching ""