Formatted question description:

 380	Insert Delete GetRandom O(1)

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

 insert(val): Inserts an item val to the set if not already present.
 remove(val): Removes an item val from the set if present.
 getRandom: Returns a random element from current set of elements.
            Each element must have the same probability of being returned.


 // Init an empty set.
 RandomizedSet randomSet = new RandomizedSet();

 // Inserts 1 to the set. Returns true as 1 was inserted successfully.

 // Returns false as 2 does not exist in the set.

 // Inserts 2 to the set, returns true. Set now contains [1,2].

 // getRandom should return either 1 or 2 randomly.

 // Removes 1 from the set, returns true. Set now contains [2].

 // 2 was already in the set, so return false.

 // Since 2 is the only number in the set, getRandom always return 2.

 Follow up:
    Could you implement the functions of the class with each function works in average O(1) time?



Use a one-dimensional array and a HashMap, where the array is used to store the numbers, and the HashMap is used to establish the mapping between each number and its position in the array.

For insert operation, first check whether this number already exists in HashMap,

  • If it exists, return false directly,
  • If it does not exist, insert it at the end of the array, and then create a mapping between the number and its position.

The delete operation is tricky. It is necessary to determine whether it is in the HashMap first,

  • If not, return false directly. Because the deletion of HashMap is constant time, but the array is not, in order to make the deletion of the array also constant level, in fact, the number to be deleted and the last number of the array are exchanged, and then the value in the corresponding HashMap is modified. You only need to delete the last element of the array, which ensures deletion within a constant time.

Returning a random number is very simple for an array, as long as a position is randomly generated, the number at that position is returned.



public class Insert_Delete_GetRandom_O_1 {

    public static void main(String[] args) {

        Insert_Delete_GetRandom_O_1 out = new Insert_Delete_GetRandom_O_1();

        // Init an empty set.
        RandomizedSet randomSet = RandomizedSet();




    class RandomizedSet {

        List<Integer> list;
        Map<Integer, Integer> map; // val => its index in list
        Random random;

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

        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            if (map.containsKey(val)) {
                return false;

            int pos = list.size();

            map.put(val, pos);

            return true;

        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if (!map.containsKey(val)) {
                return false;

            // swap val to end of list, then remove it
            int pos = map.get(val);
            int lastVal = list.get(list.size() - 1);

            list.set(pos, lastVal);
            list.remove(list.size() - 1);

            map.put(lastVal, pos); // @note: missed this line

            return true;

        /** Get a random element from the set. */
        public int getRandom() {
            int randIndex = random.nextInt(list.size());
            return list.get(randIndex);

 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();

All Problems

All Solutions