We'll start with a pretty simple challenge. Write a function called symmetricDifference that takes in two arrays and returns an array containing the symmetric difference of the two arrays. The symmetric difference of two arrays is a new array containing only the elements that are present in one of the arrays but not both, with no duplicates.
/**
* Returns an array containing the symmetric difference of two arrays.
* @param {number[]} arr1 - The first array of integers.
* @param {number[]} arr2 - The second array of integers.
* @returns {number[]} - The array containing the symmetric difference of the two arrays.
*/
function symmetricDifference(arr1: number[], arr2: number[]): number[]symmetricDifference([1, 2, 3], [3, 4, 5]);
// Output: [1, 2, 4, 5]
symmetricDifference([1, 2, 2, 3, 4], [2, 3, 3, 4, 5]);
// Output: [1, 5]
symmetricDifference([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]);
// Output: []
symmetricDifference([1, 2, 3], [4, 5, 6]);
// Output: [1, 2, 3, 4, 5, 6]- You can use two Sets to keep track of elements in both arrays and then find the elements that are present in only one of the sets.
- Be mindful of duplicate elements and handle them appropriately.
Click For Solution
function symmetricDifference(arr1, arr2) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const result = [];
for (const num of arr1) {
if (!set2.has(num)) {
result.push(num);
}
}
for (const num of arr2) {
if (!set1.has(num)) {
result.push(num);
}
}
return result;
}- To find the symmetric difference, create two
Setobjects,set1andset2, fromarr1andarr2respectively. TheSetdata structure allows us to efficiently check for the existence of an element. - Initialize an empty array called
resultto store the symmetric difference. - Iterate through each element in
arr1using afor...ofloop. For each element inarr1, we use thehas()method ofset2to check if the element exists inset2. If the element is not found inset2, it means it is present inarr1but not inarr2, and push it into theresultarray. - Similarly, iterate through each element in
arr2using anotherfor...ofloop. For each element inarr2, we use thehas()method ofset1to check if the element exists inset1. If the element is not found inset1, it means it is present inarr2but not inarr1, and push it into theresultarray. - Return the
resultarray, which contains the elements that are present in only one of the input arrays, with no duplicates.
test('Symmetric Difference of Two Arrays', () => {
expect(symmetricDifference([1, 2, 3], [3, 4, 5])).toEqual([1, 2, 4, 5]);
expect(symmetricDifference([1, 2, 2, 3, 4], [2, 3, 3, 4, 5])).toEqual([1, 5]);
expect(symmetricDifference([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])).toEqual([]);
expect(symmetricDifference([1, 2, 3], [4, 5, 6])).toEqual([1, 2, 3, 4, 5, 6]);
});