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)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay