Accepted with Latest testcases: Java soln using HashMap, Deque, ArrayList

  • 0
      // Using a double ended queue(Deque) to keep track of the indices for the duplicate elements
        List<Integer> list;
        Map<Integer, Deque<Integer>> map;
        Random rand = new Random();
        /** Initialize your data structure here. */
        public RandomizedCollection() {
            list = new ArrayList<>();
            map = new HashMap<>();
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        public boolean insert(int val) {
            boolean contain = map.containsKey(val);
            if(!contain) map.put(val, new ArrayDeque<>());
            return !contain;
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        public boolean remove(int val) {
            if(!map.containsKey(val)) return false;
            int loc = map.get(val).peekLast();
            if(loc < (list.size()-1)){
                int lastKey = list.get(list.size()-1);
                list.set(loc, lastKey);
                // removing from the last and adding in the front so that we don't keep changing index for the same element
            if(map.get(val).isEmpty()) map.remove(val);
            return true;
        /** Get a random element from the collection. */
        public int getRandom() {
            return list.get(rand.nextInt(list.size()));

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.