Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Insert Delete GetRandom O(1) - Duplicates allowed

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "381" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element. Implement the RandomizedCollection class: RandomizedCollection() Initializes the empty RandomizedCollection object. bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise. bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them. int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains. You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection. Example 1: Input ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []] Output [null, true, false, true, 2, true, 1] Explanation RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. Constraints: -231 <= val <= 231 - 1 At most 2 * 105 calls in total will be made to insert, remove, and getRandom. There will be at least one element in the data structure when getRandom is called.

Explanation

Here's a breakdown of the solution:

  • Core Data Structures: Use a list to store the elements and a dictionary to store the indices of each element within the list. This allows for O(1) average time complexity for insert, remove and getRandom operations.
  • Efficient Removal: When removing an element, swap it with the last element in the list. This avoids shifting elements, which would result in O(n) time complexity.
  • Index Management: Maintain the dictionary of indices to allow efficient location and update when swapping elements during removal.

  • Runtime Complexity: O(1) average for insert, remove, and getRandom. Storage Complexity: O(n), where n is the number of elements inserted.

Code

    import random

class RandomizedCollection:

    def __init__(self):
        self.nums = []
        self.idx = {}

    def insert(self, val: int) -> bool:
        self.nums.append(val)
        if val in self.idx:
            self.idx[val].add(len(self.nums) - 1)
            return False
        else:
            self.idx[val] = {len(self.nums) - 1}
            return True

    def remove(self, val: int) -> bool:
        if val not in self.idx or not self.idx[val]:
            return False

        remove_idx = self.idx[val].pop()
        last_idx = len(self.nums) - 1
        last_val = self.nums[last_idx]

        if remove_idx != last_idx:
            self.nums[remove_idx] = last_val
            self.idx[last_val].add(remove_idx)
            self.idx[last_val].remove(last_idx)

        self.nums.pop()
        return True

    def getRandom(self) -> int:
        return random.choice(self.nums)

More from this blog

C

Chatmagic blog

2894 posts