Skip to content

Files

Latest commit

 

History

History
73 lines (60 loc) · 1.91 KB

0380. Insert Delete GetRandom O(1).md

File metadata and controls

73 lines (60 loc) · 1.91 KB
Screen Shot 2023-08-08 at 2 18 56 AM Screen Shot 2023-08-08 at 2 19 05 AM
var RandomizedSet = function() {
    this.map = new Map();   // Map to store value and its index in the array
    this.array = [];        // Array to store values
};

/** 
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.insert = function(val) {
    if (this.map.has(val)) {
        return false;  // If val is already in the map, return false
    }

    // Otherwise, add val to the array and map
    this.array.push(val);
    this.map.set(val, this.array.length - 1);
    return true;
};

/** 
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.remove = function(val) {
    if (!this.map.has(val)) {
        return false;  // If val is not in the map, return false
    }

    // Get the index of val in the array
    let index = this.map.get(val);
    let last = this.array[this.array.length - 1];

    // If val is not the last value in the array, swap it with the last value
    if (val !== last) {
        this.array[index] = last;
        this.map.set(last, index);
    }

    // Remove val from the array and map
    this.array.pop();
    this.map.delete(val);

    return true;
};

/*
[1, 2, 3]
*/

/**
 * @return {number}
 */
RandomizedSet.prototype.getRandom = function() {
    // Get a random index between 0 and array.length - 1
    let index = Math.floor(Math.random() * this.array.length);
    return this.array[index];
};

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