Algorithms - Find the Symmetric Difference

Tell us what’s happening:

Can anyone tell why my code isn’t passing the tests?

As clunky as it is my code seems to be returning the correct output for the inputs given. I am copying and pasting each input directly and logging the output.

I have since come up with a better solution using reduce but it would still help to know what’s wrong here.

Your code so far

function sym(...args) {
  let sorted = []
  let longest = {length:0,i:0}
  let result = []

  for(let i=0;i < args.length;i++){
    let temp = args[i]
    if(args[i].length > longest.length){
      longest.length = args[i].length
      longest.i = i
    }

    let t = args[i]
    let o = Object.fromEntries(t.map(key => [key,key]))
    let a = Object.keys(o).map(key => o[key])

    sorted.push(a.sort(function(a,b){return a - b}))
  }

  let a = sorted.shift()
  let b = sorted.shift()
  
  result = [findDiff(a,b),...sorted]

  if(result.length < 2) {
    console.log("ARGUMENTS: ",...args)
    console.log("RESULTS",result[0])
    
    return result[0]
  }else
    sym(...result)
}

function findDiff(a,b){
  let result = []  
  
  while(a.length > 0 && b.length > 0){
    if(a[0] === b[0]){
      a.shift()
      b.shift()
    }else if(a[0] < b[0]){
      if(result.indexOf(a[0]) < 0)
        result.push(a[0])
      a.shift()
    }else{
      if(result.indexOf(a[0]) < 0)
        result.push(b[0])
      b.shift()
    }
  }

  result = [...result,...a,...b]
  return result
}
sym([1, 2, 5], [2, 3, 5], [3, 4, 5])

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36

Challenge Information:

Algorithms - Find the Symmetric Difference

It looks the problem is when there’s more than two sets to find difference. What part of code is responsible for returning result in such case?

It checks the first two sets, then replaces them with the result, if there is more than one set left, I use recursion to do it again until there is only the result left.

And what happens with the results of the recursive calls?

1 Like

The results from the recursive call is concatenated with the remainder sets that haven’t been calculated yet:

after that, it is checked to see if the array contains more than 1 set as I quoted above.

As far as I can tell, for any given input, the output is correct.

For the first test that breaks, the input is:
sym([1, 2, 5], [2, 3, 5], [3, 4, 5])

My logs say:
ARGUMENTS: [ 1, 2, 5 ] [ 2, 3, 5 ] [ 3, 4, 5 ]
ARGUMENTS: [ 1, 3 ] [ 3, 4, 5 ]
RESULTS [ 1, 4, 5 ]

But the test fails.

But there’s no return value from this call?

1 Like

AH THANK YOU!

I was a bit dense.

return sym(…result)

FIXED IT!