DEV Community

loading...

Discussion on: Daily Challenge #273 - Remove Duplicates

Collapse
kallmanation profile image
Nathan Kallman • Edited

Javascript in O(n) (more specifically 3n, looping three times on the length of the input, two identical reduce es and one filter):

const identity = (i) => i || i === 0;
const radixPush = (array, radix, value) => {
  array[radix] = value;
  return array;
};

const solve = (array) => array.reduce(radixPush, []).reduce(radixPush, []).filter(identity);
Collapse
qm3ster profile image
Mihail Malo • Edited

Epic, but also this relies on the array being sparse in the first reduce (so, a map really), since new Array(Number.MAX_SAFE_INTEGER) is an error.

I'd express that as

const solve = arr => {
  const vals = new Map(function * () {for (let i=0; i < arr.length; i++) yield [arr[i], i]} ())
  const out = new Array(arr.length)
  for (const [v, i] of vals) out[i] = v
  return out.filter(x => typeof x !== "undefined")
}

which is just a funny version of

const solve = arr => {
  const vals = new Map() // tfw no Map::with_capacity
  for (let i=0; i < arr.length; i++) vals.set(arr[i], i)
  const out = new Array(arr.length)
  for (const [v, i] of vals) out[i] = v
  return out.filter(x => typeof x !== "undefined")
}