Insert Delete getRandom O(1)

How to Solve Insert Delete getRandom O(1)

Insert Delete getRandom O(1) Introduction

The Insert Delete getRandom O(1) problem involves implementing a class that enables the insertion, deletion, and retrieval of a random element in constant time. Solving this design task requires a strong understanding of the operational time complexities for arrays and hash maps.

Insert Delete getRandom O(1) Problem

Design and implement an efficient sampler that can handle the following operations in constant time:

Implement the functions of the class such that each function works in average O(1) time complexity.

Example Inputs and Outputs

Example 1

Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]

[[], ["a"], ["b"], ["b"], [], ["a"], ["b"], []]

Output: [null, true, false, true, 'b', true, false, 'b']

Explanation:

Constraints

Insert Delete getRandom O(1) Solutions

When writing code to store data we have lots of data structures to choose from: arrays / lists, trees, graphs, hashmaps, linked lists, sets, etc. And different data structures have different time complexities for various operations, so depending on what we are trying to achieve, the “right” data structure to use will change. In this problem, we need to achieve O(1) for insert, remove and getRandom. Because of this requirement, let’s focus on two widely used data structures that have certain O(1) operations: hashmaps and arrays.

Back to our problem at hand, based on the time complexities above we can use a hashmap to achieve O(1) inserts and deletes, but a hashmap alone will not be sufficient for getting a random element. Likewise, we can use an array to get a random element but cannot use an array alone for O(1) reads and deletes. Since there is no limitation on space usage, we can combine both data structures in our implementation:

  1. Use a hashmap to memorize the positions for all the items in the array to achieve O(1) read and delete.
  2. Use an array to get a random element with O(1).

Approach 1: Hashmap + Array

For add operations, we can:

For delete operations, we can:

For getRandom operations, we can:

Insert Delete getRandom O(1) Python Solution - Hashmap + Array

from random import randint

class RandomizedSet(object):

def __init__(self):
        # Key is the string, value is the index of the string inside the array
        # Use this hashmap to keep track of the position of the string in the array
        self.item_to_index = {}

# The array of strings we have inserted
        self.item_arr = []

def insert(self, item):
        # Only insert if the string does not already exist
        if item in self.item_to_index:
            return False

# Append this new string to the end of the array
        index = len(self.item_arr)
        self.item_to_index[item] = index
        self.item_arr.append(item)

return True

def remove(self, item):
        # Only remove if the string exists
        if item not in self.item_to_index:
            return False

# Swap the string to be removed to the end of the array
        index = self.item_to_index[item]
        last_item = self.item_arr[-1]
        self.item_to_index[last_item] = index
        self.item_arr[index] = last_item
        self.item_arr.pop()
        del self.item_to_index[item]

return True

def getRandom(self):
        # Randomly pick an index available
        index = randint(0, len(self.item_arr) - 1)
        return self.item_arr[index]

Time/Space Complexity