Write a function `intersection(arr1, arr2)` that returns an array of values present in both arrays (unique).
Problem Statement
Examples
Input: arr1 = [1, 2, 2, 1], arr2 = [2, 2]
Output: [2]
Explanation: 2 is the unique element present in both arrays.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Find Intersection of Two Arrays, we consider the execution characteristics of JavaScript engines. Write a function `intersection(arr1, arr2)` that returns an array of values present in both arrays (unique). By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use set for efficient lookup).
- Implement Logic: Handle state and transformations efficiently (filter arr1 by checking if each element exists in a set created from arr2).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function intersection(arr1, arr2) {
const set = new Set(arr2);
return [...new Set(arr1.filter(x => set.has(x)))];
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.