DEV Community

loading...

Discussion on: Leetcode Daily - Find all duplicates in an array

Collapse
functional_js profile image
Functional Javascript

Nice work Andrew.

I did a robustness-test and a perf-test and made some adjustments...

/*
@func
get the uniq list of dups in arr

@notes
also applies to empty strs
filters out nils

@param {string[]|number[]} a - of prims, i.e. strings or numbers
@return {string[]|number[]} uniq list of dups from orig arr
*/
const findDups = a => {
  let hash = {}; // hash table of seen vals
  let dupes = []; //final
  for (let i = 0; i < a.length; i++) { // now go through the arr once
    if (isNil(a[i])) {
      continue;
    }
    if (hash[a[i]]) {
      dupes.push(a[i]) // already seen, so add to dupes
    } else {
      hash[a[i]] = true; // first time seen, add it to hash of seen vals
    }
  }
  return dupes;
};

//@tests
const a = [
  [1, 2, 3, 2, 3],
  [1, 2, 3],
  [0, 0, 3],
  [0, 0, 3, -1, -1],
  [],
  ["one", "two", "Two"],
  ["one", "two", "two"],
  ["", "", "two"],
  [null, undefined, "two"],
  [null, undefined, null, undefined, "two"],
];
logForeachParam(findDups, a);
/*
@output
 [ 2, 3 ]
 []
 [ 0 ]
 [ 0, -1 ]
 []
 []
 [ 'two' ]
 [ '' ]
[]
[]
*/

//@perftest
timeInLoop("findDups", 1e6, () => findDups([1, 2, 3, 2, 3]));
/*
@output
findDups: 1e+6: 993.192ms  - without toString()
findDups: 1e+6: 1.618s - with toString()
*/

Forem Open with the Forem app