Single Number | LeetCode 136

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard


Here is the full implementation.

/**
 * @param {number[]} nums
 * @return {number}
 */
let singleNumber = function(nums) {
  let set = new Set(); // use a set for O(1) lookups

  for (num of nums) {
    /* add the number if it's not in the set, but remove it if it is. this way, after every number has been iterated over, the only number remaining is the number that only shows up once */
    if (set.has(num)) {
      set.delete(num);
    } else {
      set.add(num);
    }
  }

  // there will only be one number remaining in the set. return it
  return Array.from(set)[0];   
};