Explorer
JavaScript

Write functions `union(a, b)`, `intersect(a, b)`, and `difference(a, b)` for arrays treated as sets.

Problem Statement

<p>Write functions <code>union(a, b)</code>, <code>intersect(a, b)</code>, and <code>difference(a, b)</code> for arrays treated as sets.</p>

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

šŸ’” Hint 1: Use Set for efficient lookups. šŸ’” Hint 2: Union: combine both. Intersect: elements in both. Difference: elements in a but not in b. šŸ’” Hint 3: Convert to Sets and use filter/spread for each operation.

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (use set for efficient lookups).
  3. Implement Logic: Handle state and transformations efficiently (union: combine both. intersect: elements in both. difference: elements in a but not in b).
  4. 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

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

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.

Implement Set Operations

Medium

Write functions union(a, b), intersect(a, b), and difference(a, b) for arrays treated as sets.

Example Scenarios
1Example 1
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.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"union":[1,2,3,4,5,6],"intersect":[3,4],"difference":[1,2]}