Middle
JavaScript task: write a function that takes two arrays and returns an array of elements present only in one of the arrays (symmetric difference). Assess the algorithm's complexity.
sobes.tech AI
Answer from AI
Here is an example of a JavaScript function that returns the symmetric difference of two arrays:
function symmetricDifference(arr1, arr2) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const result = [];
for (const item of set1) {
if (!set2.has(item)) {
result.push(item);
}
}
for (const item of set2) {
if (!set1.has(item)) {
result.push(item);
}
}
return result;
}
The algorithm complexity is O(n + m), where n and m are the lengths of the input arrays. This is because the add and check operations in Set are performed in amortized O(1), and we iterate through each element of both arrays once.