# Insert Delete GetRandom Duplicates allowed

This page explains Java solution to problem `Insert Delete GetRandom Duplicates allowed` using `HashMap Data Structure` algorithm.

## Problem Statement

Design a data structure that supports all following operations in average `O(1)` time.

• Note: Duplicate elements are allowed.
• `insert(val)`: Inserts an item val to the collection.
• `remove(val)`: Removes an item val from the collection if present.
• `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 1:

// 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();

## Solution

If you have any suggestions in below code, please create a pull request by clicking here.
``````
package com.vc.hard;

import java.util.*;

class InsertDeleteGetRandomDuplicatesAllowed {

private HashMap<Integer, Set<Integer>> indexMap;
private List<Integer> list;
private Random random;

/** Initialize your data structure here. */
public InsertDeleteGetRandomDuplicatesAllowed() {
indexMap = new HashMap<>();
list = new ArrayList<>();
random = new Random();
}

/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean res = !indexMap.containsKey(val);

Set<Integer> set = indexMap.getOrDefault(val, new HashSet<>());
indexMap.put(val, set);

return res;
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if(indexMap.containsKey(val)) {
int removeIndex = indexMap.get(val).iterator().next();
int swapElement = list.get(list.size() - 1);

indexMap.get(val).remove(removeIndex);
indexMap.get(swapElement).remove(list.size() - 1);

if(indexMap.get(val).size() == 0) indexMap.remove(val);

list.set(removeIndex, swapElement);
list.remove(list.size() - 1);

return true;
}
return false;
}

/** Get a random element from the collection. */
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
``````

O(1)

## Space Complexity

O(N) Where
N is total number of elements in an input array