2215. Find the Difference of Two Arrays || Array || DSA
Intuition\nUsing Set objects allows us to efficiently store only the unique elements in each input array, eliminating duplicates and reducing the overall search
# Intuition\nUsing Set objects allows us to efficiently store only the unique elements in each input array, eliminating duplicates and reducing the overall search time.\nFiltering the elements using .filter() method allows us to easily find the differences between the two sets by checking if each element is in one set but not the other.\nUsing an array csm to store the difference arrays allows us to easily return both arrays as a single value.\n\n# Approach\nWe first create two Set objects set1 and set2 from the input arrays nums1 and nums2, respectively, to store the unique elements in each array.\nWe then create an empty array csm to store the two difference arrays.\nTo find the elements that are in set1 but not in set2, we filter the elements in set1 by checking if they are not in set2 using the .filter() method, and assign the filtered array to csm[0].\nSimilarly, to find the elements that are in set2 but not in set1, we filter the elements in set2 by checking if they are not in set1, and assign the filtered array to csm[1].\nFinally, we return the csm array containing the two difference arrays.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the longer input array. This is because creating the two Set objects takes O(n) time each, and filtering the arrays using .filter() takes O(n) time each. Thus, the overall time complexity is O(n + n + n + n) = O(4n) = O(n).\n\n- Space complexity: O(n), where n is the total number of unique elements in both input arrays. This is because we create two Set objects to store the unique elements in the input arrays, and the maximum size of each Set is n (when both input arrays have all unique elements). We also create an array csm to store the two difference arrays, which has a maximum size of 2n. Thus, the overall space complexity is O(2n + n) = O(3n) = O(n).\n\n# Code\n```\n\nvar findDifference = function(nums1, nums2) {\n    let set1 = new Set(nums1);\n    let set2 = new Set(nums2);\n    let csm=[];\n    csm[0]= [...set1].filter(x => !set2.has(x));\n    csm[1]= [...set2].filter(x => !set1.has(x));\n    return csm\n};\n\n```
['JavaScript']