JSFiddle - React, Tailwind, and code Playground

Insert Delete GetRandom O(1) using two hash tables: one contains indexed elements for random picks, another contains named values

by Yurii Predborskyi

JavaScript

/**
 * Initialize your data structure here.
 */
var RandomizedSet = function() {
    this.set = {};
    this.arr = { length: 0 };
};

/**
 * Inserts a value to the set. Returns true if the set did not already contain the specified element. 
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.insert = function(val) {
		console.log('insert');
    console.log('set:', this.set);
    console.log('arr:', this.arr);
		if (val === undefined) {
    	console.log('cannot insert undefined');
      return false;
    }
    if (this.set[val] === undefined) {
    	// val does not exist yet, adding val
      console.log('adding', val);
    	const index = this.arr.length++;
      this.arr[index] = val;
    	this.set[val] = index;
    console.log('new set:', this.set);
    console.log('new arr:', this.arr);
      return true;
    } else {
    	// val exists, skip
      console.log('valule exists:', val, 'not added')
	    return false;
    }
};

/**
 * Removes a value from the set. Returns true if the set contained the specified element. 
 * @param {number} val
 * @return {boolean}
 */
RandomizedSet.prototype.remove = function(val) {
  console.log('removing', val);
  console.log('set:', this.set);
  console.log('arr:', this.arr);
		if (val === undefined) {
    	console.log('cannot remove undefined');
      return false;
    }
    if (this.set[val] !== undefined && this.set[val] !== null) {
    	// val exists, removing from set
      let index = this.set[val];
      let last = this.arr.length - 1;
      if (index !== last) {
      	// replace current value with last value
	      this.arr[index] = this.arr[last];
        this.set[this.arr[index]] = index;
      }
      delete this.arr[last];
    	delete this.set[val];
      --this.arr.length;
      /* 
      check if index = last value in arr
      if so, do nothing
      else, overwrite value at index with last value in array
      */
      
			/*
			console.log('this arr index =', this.arr[index])
      delete...