Set Operations Implementer - Problem

Implement four fundamental set operations without using built-in set functions or libraries. Given two arrays representing sets (containing unique elements), implement:

  • Union: All elements that appear in either set
  • Intersection: Elements that appear in both sets
  • Difference: Elements in the first set but not the second
  • Symmetric Difference: Elements in either set but not in both

Return a 2D array where each row contains the result of one operation in the order: [union, intersection, difference, symmetric_difference].

Note: The order of elements in each result array doesn't matter, but duplicates should be eliminated.

Input & Output

Example 1 — Basic Sets
$ Input: set1 = [1,2,3], set2 = [2,4]
Output: [[1,2,3,4], [2], [1,3], [1,3,4]]
💡 Note: Union combines all unique elements [1,2,3,4]. Intersection finds common element [2]. Difference shows elements only in set1 [1,3]. Symmetric difference shows elements in exactly one set [1,3,4].
Example 2 — Disjoint Sets
$ Input: set1 = [1,3], set2 = [2,4]
Output: [[1,3,2,4], [], [1,3], [1,3,2,4]]
💡 Note: No common elements, so intersection is empty []. Union and symmetric difference are the same since sets don't overlap. Difference contains all of set1 [1,3].
Example 3 — Identical Sets
$ Input: set1 = [5,10], set2 = [5,10]
Output: [[5,10], [5,10], [], []]
💡 Note: Sets are identical. Union equals both sets [5,10]. Intersection is the full set [5,10]. Difference and symmetric difference are empty since no elements are unique to either set.

Constraints

  • 1 ≤ set1.length, set2.length ≤ 1000
  • -106 ≤ set1[i], set2[i] ≤ 106
  • All elements within each set are unique

Visualization

Tap to expand
INPUT SETS123Set 1: [1, 2, 3]24Set 2: [2, 4]FREQUENCY MAP1Count frequencies:21→1, 2→1 from Set132→2, 4→1 from Set24Final: {1:1, 2:2, 3:1, 4:1}FOUR RESULTSUnion (all): [1,2,3,4]Intersection (both): [2]Difference (Set1 only): [1,3]Symmetric Diff: [1,3,4]Output Format[[1,2,3,4], [2], [1,3], [1,3,4]]Key Insight:Frequency counting reveals set relationships: elements with count=1 belong to one set,count=2 belong to both sets, enabling all four operations in a single pass.TutorialsPoint - Set Operations Implementer | Hash Map Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.4K Views
Medium Frequency
~15 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen