Write functions `union(a, b)`, `intersect(a, b)`, and `difference(a, b)` for arrays treated as sets.
Problem Statement
Examples
Input: union([1, 2], [2, 3]); intersect([1, 2], [2, 3]); difference([1, 2], [2, 3])
Output: union: [1,2,3], intersect: [2], diff: [1]
Explanation: Standard set algebraic operations.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Implement Set Operations, we consider the execution characteristics of JavaScript engines. Write functions `union(a, b)`, `intersect(a, b)`, and `difference(a, b)` for arrays treated as sets. 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 lookups).
- Implement Logic: Handle state and transformations efficiently (union: combine both. intersect: elements in both. difference: elements in a but not in b).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function setOps(a, b) {
const setA = new Set(a);
const setB = new Set(b);
return {
union: [...new Set([...a, ...b])],
intersect: a.filter(x => setB.has(x)),
difference: a.filter(x => !setB.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.