Coding Interview Prep: Algorithms - Find the Symmetric Difference (freeCodeCamp)

 Find the Symmetric Difference

The mathematical term symmetric difference ( or ) of two sets is the set of elements which are in either of the two sets but not in both. For example, for sets A = {1, 2, 3} and B = {2, 3, 4}A △ B = {1, 4}.

Symmetric difference is a binary operation, which means it operates on only two elements. So to evaluate an expression involving symmetric differences among three elements (A △ B △ C), you must complete one operation at a time. Thus, for sets A and B above, and C = {2, 3}A △ B △ C = (A △ B) △ C = {1, 4} △ {2, 3} = {1, 2, 3, 4}.


Create a function that takes two or more arrays and returns an array of their symmetric difference. The returned array must contain only unique values (no duplicates).

Solution:
function sym(...args) {
  let arr = args;
  if(arr.length < 2) {
    return false;
  }
  let diff = twoArr(arr[0], arr[1])
  if (arr.length === 2) {
    return diff;
  }
  let result = diff
  for(let i = 2i < arr.lengthi++) {
      result = twoArr(result,arr[i])
  }
  
  function twoArr(x,y) {
    let res = [];
    for (let i = 0i<x.lengthi++){
      if(!y.includes(x[i]) && !res.includes(x[i])){
        res.push(x[i])
      }    
    }

    for (let i = 0i<y.lengthi++){
      if(!x.includes(y[i]) && !res.includes(y[i])){
        res.push(y[i])
      }    
    }
    return res;
  }

  return result;
}

sym([33325], [2157], [3466], [123]);




PS: There can be multiple ways to solve this problem.
Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post