sophryu99 / algorithm

algorithm in python - 4 questions a week

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

380. Insert Delete GetRandom O(1)

sophryu99 opened this issue · comments

commented

Approach

https://leetcode.com/problems/insert-delete-getrandom-o1/description/

The intuition would be to create a set for O(1) operation. However, since there is the function getRandom(), creating a set is not efficient as we would first need to convert to list, which will be an overhead for the whole code. This is because set is actually not random as when using integers, elements are popped from the set in the order they appear in the underlying hashtable.

  1. Use a dict and a list
  2. Dict as {int element: index}, and list to keep track of unique int elements
  3. When remove is called, swap the last element of the list with the to-be-removed element
  4. Swap the index of the two elements in the dictionary's index
  5. Pop from the list, and remove from the dict
import random
class RandomizedSet:
    def __init__(self):
        self.d = {}
        self.l = []

    def insert(self, val: int) -> bool:
        if val not in self.d:
            # Store the index of the int ele
            self.d[val] = len(self.l)
            self.l.append(val)
            return True
        return False
        
    def remove(self, val: int) -> bool:
        if val not in self.d:
            return False
        
        l_ele = self.l[-1]
        r_index = self.d[val]

        # Replace the index
        self.d[l_ele] = r_index
        self.l[r_index] = l_ele
        
        # Remove from list and dict
        self.l[-1] = val
        self.l.pop()
        self.d.pop(val)
        return True

    def getRandom(self) -> 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()

Example

element_to_remove = 7

before:     [4, 7, 9, 3, 5]
after:      [4, 5, 9, 3]

before:     {4:0, 7:1, 9:2, 3:3, 5:4}
after:      {4:0, 9:2, 3:3, 5:1}

n: array size

  • Time Complexity: O(1) with pop, add and get random operation
  • Space Complexity: O(n) with dict and list