본문 바로가기

Algorithm

[Leetcode] 381. Insert Delete GetRandom O(1) - Duplicates allowed

Design a data structure that supports all following operations in average O(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();

 

단순 set 을 사용해서는 O(1) 에 똑같은 확률의 getRandom() method 를 구현하기가 어렵다.

 

getRandom() 이 가능하려면 random 으로 설정된 index 에 대해 index 로 접근이 가능해야 한다.

 

즉, array 형식의 list 여야 한다.

그렇다면 array 에 insert, remove 를 어떻게 O(1) 에 제공할까?

 

ArrayList 의 add 는 상환시간 계산으로 인해 O(1) 를 제공하지만, remove 는 O(n) 에 수행된다.

단, 맨 마지막 index 를 삭제할때는 나머지 노드를 당길 필요가 없으므로, O(1) 을 제공할 수 있다.

 

  1. 삭제할 index 를 찾고, 삭제할 index 의 위치가 마지막 index 가 아니라면,
  2. 맨 끝에 index 에 있는 값을 삭제할 target index 에 넣는다.
  3. 그리고 맨 마지막 index 에 있는 값을 삭제한다.
import java.util.*;

public class RandomizedCollection {
    List<Integer> list;
    Map<Integer, Set<Integer>> map;
    Random random;

    /** Initialize your data structure here. */
    public RandomizedCollection() {
        this.list = new ArrayList<>();
        this.map = new HashMap<>();
        this.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) {
        list.add(val);

        boolean contains = map.containsKey(val);

        map.computeIfAbsent(val, t -> new HashSet<>()).add(list.size()-1);

        return contains == false;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    public boolean remove(int val) {
        if (map.getOrDefault(val, new HashSet<>()).size() == 0) {
            return false;
        }

        int lastIndex = list.size() - 1;
        int targetIndex = map.get(val).iterator().next();

        int lastVal = list.get(lastIndex);
        int targetVal = list.get(targetIndex);


        // or !map.get(val).contains(list.size() -1) 도 가능하다.
        // val 이 가지고 있는 index 에 마지막 index 가 포함되어 있는지를 확인해야 한다.
        if (targetIndex < lastIndex && lastVal != targetVal) {
            // 맨 마지막 index 의 값을 targetIndex 위치에 넣는다.
            list.set(targetIndex, lastVal);

            // map 에서 맨 마지막 value 의 index 의 값을 갱신한다.
            map.get(lastVal).remove(lastIndex);
            map.get(lastVal).add(targetIndex);

            // map 에서 타겟 value 의 index 값을 갱신한다.
            map.get(targetVal).remove(targetIndex);
            map.get(targetVal).add(lastIndex);
        }

        list.remove(lastIndex);
        map.get(val).remove(lastIndex);
        return true;
    }

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

    public static void main(String[] args) {
        RandomizedCollection collection = new RandomizedCollection();

        System.out.println(collection.insert(4));
        System.out.println(collection.insert(3));
        System.out.println(collection.insert(4));
        System.out.println(collection.insert(2));
        System.out.println(collection.insert(4));

        System.out.println(collection.remove(4));
        System.out.println(collection.remove(3));
        System.out.println(collection.remove(4));
        System.out.println(collection.remove(4));
    }
}