Algorithm


Problem Name: 381. Insert Delete GetRandom O(1) - Duplicates allowed

Problem Link: https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/

 

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

 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class RandomizedCollection {

    Map list;

    public RandomizedCollection() {
        map = new HashMap<>();
        list = new ArrayList < >();
    }

    public boolean insert(int val) {
        map.computeIfAbsent(val, k -> new LinkedHashSet<>()).add(list.size());
        list.add(val);
        return map.get(val).size() == 1;
    }

    public boolean remove(int val) {
        if (!map.containsKey(val) || map.get(val).size() == 0) {
            return false;
        }

        int idxToRemove = map.get(val).iterator().next();
        map.get(val).remove(idxToRemove);
        int lastVal = list.get(list.size() - 1);
        list.set(idxToRemove, lastVal);
        map.get(lastVal).add(idxToRemove);
        map.get(lastVal).remove(list.size() - 1);
        list.remove(list.size() - 1);
        
        return true;
    }

    public int getRandom() {
        return list.get(new java.util.Random().nextInt(list.size()));
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []]

Output

x
+
cmd
[null, true, false, true, 2, true, 1]

#2 Code Example with Javascript Programming

Code - Javascript Programming


const RandomizedCollection = function() {
  this.map = new Map()
  this.list = []
}

RandomizedCollection.prototype.insert = function(val) {
  const index = this.list.length
  const node = { val, index }
  this.list[index] = node

  const nodeList = this.map.get(val)
  const isNew = nodeList === undefined || nodeList.length === 0
  if (nodeList === undefined) {
    this.map.set(val, [node])
  } else {
    nodeList.push(node)
  }
  return isNew
}

RandomizedCollection.prototype.remove = function(val) {
  const nodeList = this.map.get(val)
  if (!nodeList || nodeList.length === 0) return false
  const node = nodeList.pop()
  const replacement = this.list.pop()
  if (replacement.index !== node.index) {
    replacement.index = node.index
    this.list[replacement.index] = replacement
  }
  return true
}

RandomizedCollection.prototype.getRandom = function() {
  const index = Math.floor(Math.random() * this.list.length)
  return this.list[index].val
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []]

Output

x
+
cmd
[null, true, false, true, 2, true, 1]

#3 Code Example with Python Programming

Code - Python Programming


class RandomizedCollection:

    def __init__(self):
        self.arr, self.pos = [], collections.defaultdict(set)
    def insert(self, val):
        out = val not in self.pos
        self.arr.append(val)
        self.pos[val].add(len(self.arr) - 1)
        return out

    def remove(self, val):
        if val in self.pos:
            if self.arr[-1] != val:
                x, y = self.pos[val].pop(), self.arr[-1]
                self.pos[y].discard(len(self.arr) - 1)
                self.pos[y].add(x)
                self.arr[x] = y
            else:
                self.pos[val].discard(len(self.arr) - 1)
            self.arr.pop()
            if not self.pos[val]:
                self.pos.pop(val)
            return True 
        return False

    def getRandom(self):
        return random.choice(self.arr)
Copy The Code & Try With Live Editor

Input

x
+
cmd
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []]

Output

x
+
cmd
[null, true, false, true, 2, true, 1]

#4 Code Example with Python Programming

Code - Python Programming


using System;
using System.Collections.Generic;
using System.Linq;

namespace LeetCode
{
    public class _0381_InsertDeleteGetrandomDuplicatesAllowed
    {
        private readonly Random random;
        private readonly IDictionary < int, ISet<int>> locations;
        private readonly IList < int> nums;

        public _0381_InsertDeleteGetrandomDuplicatesAllowed()
        {
            random = new Random();
            locations = new Dictionary < int, ISet<int>>();
            nums = new List < int>();
        }

        public bool Insert(int val)
        {
            if (!locations.ContainsKey(val))
                locations[val] = new HashSet<int>();

            locations[val].Add(nums.Count);
            nums.Add(val);
            return locations[val].Count == 1;
        }

        public bool Remove(int val)
        {
            if (!locations.ContainsKey(val)) return false;

            var id = locations[val].First();
            locations[val].Remove(id);

            var num = nums[nums.Count - 1];
            nums[id] = num;
            locations[num].Add(id);
            locations[num].Remove(nums.Count - 1);
            nums.RemoveAt(nums.Count - 1);

            if (locations[val].Count == 0) locations.Remove(val);

            return true;
        }

        /** Get a random element from the collection. */
        public int GetRandom()
        {
            var id = random.Next(nums.Count);
            return nums[id];
        }
    }

}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []]

Output

x
+
cmd
[null, true, false, true, 2, true, 1]
Advertisements

Demonstration


Previous
#380 Leetcode Insert Delete GetRandom O(1) Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#383 Leetcode Ransom Note Solution in C, C++, Java, JavaScript, Python, C# Leetcode