Https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/find-the-symmetric-difference

I’ve created an algorithm for the ‘Algorithms: Find the Symmetric Difference’ challenge. From what I can tell, this should be returning the correct answer for at LEAST the first test input. However, it’s claiming the returned output is incorrect. Anyone able to help me unpack the reason why?

My code:


function sym(args) {
args = arguments;
sym = [];
for (var a = 0; a < args.length; a++) {
  for (var index of args[a]) {
    sym.push(index);
  }
}

var temp = 0;
for (var b = 0; b < sym.length; b++) {
  for (var c = 0; c < sym.length; c++) {
    if (sym[c] > sym[c+1]) {
      temp = sym[c+1];
      sym[c+1] = sym[c];
      sym[c] = temp;
    }
  }
}

for (var d = 1; d < sym.length; d++) {
  if (sym[d-1] == sym[d]) {
    delete sym[d-1];
    delete sym[d];
  }
}

var arr = [];
for (var element of sym){
  if (!isNaN(element)) 
    arr.push(element);
}
args = arr;
return args;
}

sym([1, 2, 3], [5, 2, 1, 4]);

Your browser information:

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

Challenge: Find the Symmetric Difference

Link to the challenge:

The second part of your code just sorts the now-combined array, it doesn’t check for or remove duplicates. You can see what I mean if you change it to:

var temp = 0;
for (var b = 0; b < sym.length; b++) {
  for (var c = 0; c < sym.length; c++) {
    if (sym[c] > sym[c+1]) {
      temp = sym[c+1];
      sym[c+1] = sym[c];
      sym[c] = temp;
    }
  }
  console.log(sym)
}

Yes, that is not the section where the duplicates are removed.

My code begins by sorting the array, afterward is looks for duplicates beside eachother and deletes them. Finally, it takes all the remaining numbers of the array into another array without out the null indexes and returns that array.

IDK if you’re still looking for help on this, probably not, but:

  1. You’re right, I should’ve scrolled further down to see the purging function, but
  2. Purging function only works with two arrays. More than two and it doesn’t know the source. Example:
console.log(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]));

returns

[ 2, 3, 4, 7 ]

Which is not correct.

Finally, and I have no idea why, if I run your function more than once, I get a “sym is not a function” error. E.g.,

console.log(sym([1, 2, 3], [5, 2, 1, 4]));
console.log(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]));

gives me

[ 3, 4, 5 ]
TypeError: sym is not a function

That may be worth putting on the Git as an error. IDK the cause.