Categories
interview

Subsets with no duplicates

Generate subsets with no duplicates.

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
const subsetsWithDup = (nums) => {
  if (!nums) {
    return;
  }

  const len = nums.length;
  const ret = [];
  const subsetStore = {};

  for (let i = 0; i < (1 << len); i++) {
    const currSubset = [];

    for (let j = 0; j < len; j++) {
      if ((1 << j) & i) {
        currSubset.push(nums[j]);
      }
    }

    const subsetKey = [...currSubset].sort((a,b) => a - b).join('.');

    if (!(subsetKey in subsetStore)) {
      ret.push(currSubset);
      subsetStore[subsetKey] = true;
    }

  }

  return ret;
};

console.log(subsetsWithDup([1,1,2]));
// [[], [1], [1, 1], [2], [1, 2], [1, 1, 2]]

Demo