/**
* Finds the unique intersection of two arrays (values present in both).
* Preserves the relative order of elements as they first appear in the first array.
*
* @template T - The element type of the arrays.
* @param {readonly T[]} first - The first input array.
* @param {readonly T[]} second - The second input array.
* @returns {T[]} Array containing unique common elements.
*
* Time Complexity: O(n + m) where n and m are the lengths of the input arrays.
* Space Complexity: O(m) to store the lookup Set.
*/
export function findArrayIntersection<T>(
first: readonly T[],
second: readonly T[]
): T[] {
// 1. Load the second array into a Set for fast O(1) membership lookups
const lookupSet: Set<T> = new Set<T>(second);
// 2. Track processed matches to prevent duplicate values in the result
const seenSet: Set<T> = new Set<T>();
const result: T[] = [];
// 3. Iterate through the first array to preserve original element ordering
for (const item of first) {
if (lookupSet.has(item) && !seenSet.has(item)) {
result.push(item);
seenSet.add(item);
}
}
return result;
}
// --- Usage Example ---
const arr1: number[] = [5, 7, 1, 1, 3, 0, 6, 2];
const arr2: number[] = [2, 8, 8, 6, 9, 3, 3, 4, 4];
const intersection: number[] = findArrayIntersection(arr1, arr2);
console.log("Arr1: ", arr1);
console.log("Arr2: ", arr2);
console.log("Intersection:", intersection); // Output: [3, 6, 2]
/*
run:
Arr1: [
5, 7, 1, 1,
3, 0, 6, 2
]
Arr2: [
2, 8, 8, 6, 9,
3, 3, 4, 4
]
Intersection: [ 3, 6, 2 ]
*/