Intern
What is array intersection?
sobes.tech AI
Answer from AI
Array intersection is the operation of finding all elements that are present in two or more arrays.
// Example of intersecting two arrays
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const intersection = array1.filter(element => array2.includes(element));
console.log(intersection); // Outputs [3, 4, 5]
Main approaches to implementation:
- Using
filterandincludes: A simple and readable approach for small arrays. Performance may decrease for large arrays due to nested loops (filterandincludesin the worst case).const intersection = array1.filter(element => array2.includes(element)); - Using
Set: More efficient for large arrays, as checking for the presence of an element in aSethas an average time complexity of O(1).const set2 = new Set(array2); const intersection = array1.filter(element => set2.has(element)); - Sorting and two pointers: If arrays are sorted, you can use two pointers to traverse both arrays linearly. Has a time complexity of O(n log n) due to sorting, then O(n).
const sortedArray1 = [...array1].sort((a, b) => a - b); const sortedArray2 = [...array2].sort((a, b) => a - b); const intersection = []; let i = 0; let j = 0; while (i < sortedArray1.length && j < sortedArray2.length) { if (sortedArray1[i] === sortedArray2[j]) { intersection.push(sortedArray1[i]); i++; j++; } else if (sortedArray1[i] < sortedArray2[j]) { i++; } else { j++; } }
The choice of method depends on the size of the arrays and performance requirements. For small arrays, filter and includes are sufficient; for larger arrays, it is preferable to use Set or sorting.