DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 380. Insert Delete GetRandom O(1)


 class RandomizedSet{
    constructor() {
        this.hashMap = new Map()
        this.list = [];
    }

    insert(val){
        if(this.hashMap.has(val)){
            return false
        }
        this.hashMap.set(val, this.list.length)
        this.list.push(val);
        return true
    }

    remove(val){

            if(!this.hashMap.has(val)) return false;

            const idx = this.hashMap.get(val);

            this.list[idx] = this.list[this.list.length - 1]


            this.list.pop();

            this.hashMap.set(this.list[idx], idx)

            this.hashMap.delete(val)

            return true
    }

    getRandom(){
        return this.list[Math.floor(Math.random() * this.list.length)]
    }


 }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)