re: Javascript Sock Merchant Challenge - Solution 2 VIEW POST

TOP OF THREAD FULL DISCUSSION
re: I don't think you even need the last reducer. Just keep a running counter. function sockMerchant(n, ar) { const colors = {} let pairs = ...
 

@theodesp this was just me commenting on the code without changing the algorithm at all.
My own solution (which does use a counter) was posted separately:

My own solution would be:

function stockAndCount( n, arr ) {
  let pairs = 0
  const unpaired = new Set()

  for (const color of arr)
    if (unpaired.has(color)) {
      pairs++
      unpaired.delete(color)
    } else unpaired.add(color)

  return pairs
}

This doesn't iterate again over the colors encountered, and uses the minimal memory required for the task: The running total of pairs and the unpaired colors, encountering which again would be the completion of a pair.

code of conduct - report abuse