Insert Delete GetRandom O(1) - Duplicates allowed (Hard)

Problem is here (#424 solved in my list): https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/

Design a data structure that supports all following operations in averageO(1) time.
Note: Duplicate elements are allowed.
  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.
Example:
// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();
// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);
// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);
// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);
// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();
// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);
// getRandom should return 1 and 2 both equally likely.
collection.getRandom();
So to solve this problem I'll make use of some C# data types and assume that some of its inner operations are on average constant time (right thing to do would be to research it and make sure that this is the case - that's left as an exercise).
The approach will be the following:

  1. Keep the elements in a linked-list. Allow dupes
  2. Whenever you add an element, have a hash table pointing to the node in the list that's just been added
  3. To delete an element, use the hash table to get the node, and delete from the list using the built-in list function Delete which accepts a node as input
  4. To randomize, use the ElementAt built-in function from the list (also the count, which would be easy to implement natively)
I have scratched the solution on a (Whole Foods) paper, as you can see below. Code is down here, cheers, ACC.


public class RandomizedCollection
{
private LinkedList<LinkedListNode<int>> list = null;
private Hashtable valToNode = null;
private Random rd = null;

/** Initialize your data structure here. */
public RandomizedCollection()
{
list = new LinkedList<LinkedListNode<int>>();
valToNode = new Hashtable();
rd = new Random();
}

/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public bool Insert(int val)
{
LinkedListNode<int> node = new LinkedListNode<int>(val);
list.AddLast(node);
bool retVal = false;

if (!valToNode.ContainsKey(val))
{
LinkedList<LinkedListNode<int>> index = new LinkedList<LinkedListNode<int>>();
index.AddLast(node);
valToNode.Add(val, index);
retVal = true;
}
else
{
LinkedList<LinkedListNode<int>> index = (LinkedList<LinkedListNode<int>>)valToNode[val];
index.AddLast(node);
retVal = false;
}

return retVal;
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public bool Remove(int val)
{
if (!valToNode.ContainsKey(val)) return false;

LinkedList<LinkedListNode<int>> index = (LinkedList<LinkedListNode<int>>)valToNode[val];
LinkedListNode<int> firstNode = index.First.Value;
list.Remove(firstNode);

index.RemoveFirst();
if (index.Count == 0)
{
valToNode.Remove(val);
}

return true;

}

/** Get a random element from the collection. */
public int GetRandom()
{
int randIndex = rd.Next(0, list.Count);
return list.ElementAt<LinkedListNode<int>>(randIndex).Value;
}
}

Comments

  1. Looks great, although I think the complexity of GetRandom is not O(1), since ElementAt's complexity is linear with respect to the number of elements. I'm using vector (aka ArrayList) to get constant complexity:

    class RandomizedCollection {
    private:
    vector values;
    unordered_map> indices;
    public:
    bool insert(int val) {
    auto& val_indices = indices[val];
    val_indices.insert(values.size());
    values.push_back(val);
    return val_indices.size() == 1;
    }

    bool remove(int val) {
    auto found = indices.find(val);
    if (found == indices.cend() || found->second.empty()) {
    return false;
    }
    auto& to_remove_indices = found->second;
    auto to_remove_idx = *to_remove_indices.begin();
    to_remove_indices.erase(to_remove_idx);
    int to_insert = values.back();
    values[to_remove_idx] = to_insert;
    found = indices.find(to_insert);
    if (found != indices.cend() && !found->second.empty()) {
    indices[to_insert].erase(values.size()-1);
    indices[to_insert].insert(to_remove_idx);
    }
    values.pop_back();
    return true;
    }

    int getRandom() {
    return values[rand() % values.size()];
    }
    };

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...