Maximum Size of a Set After Removals - Problem

You are given two 0-indexed integer arrays nums1 and nums2 of even length n.

You must remove n / 2 elements from nums1 and n / 2 elements from nums2. After the removals, you insert the remaining elements of nums1 and nums2 into a set s.

Return the maximum possible size of the set s.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2,3,4], nums2 = [3,4,5,6]
Output: 4
💡 Note: Remove [3,4] from nums1 and [3,4] from nums2. Remaining: [1,2] and [5,6]. Final set: {1,2,5,6} has size 4.
Example 2 — All Common Elements
$ Input: nums1 = [1,2,1,2], nums2 = [1,1,1,1]
Output: 2
💡 Note: Remove duplicates optimally. Keep [1,2] from nums1 and [1] from nums2. Final set: {1,2} has size 2.
Example 3 — No Common Elements
$ Input: nums1 = [1,1,2,2], nums2 = [3,3,4,4]
Output: 4
💡 Note: No overlap between arrays. Keep [1,2] from nums1 and [3,4] from nums2. Final set: {1,2,3,4} has size 4.

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • n is even
  • 1 ≤ nums1[i], nums2[i] ≤ 109

Visualization

Tap to expand
Maximum Size of a Set After Removalsnums1 = [1,2,3,4]Remove 2 elementsnums2 = [3,4,5,6]Remove 2 elementsKeep: [1,2]Remove: [3,4]Keep: [5,6]Remove: [3,4]Final Set{1,2,5,6}Maximum Size: 4
Understanding the Visualization
1
Input Arrays
Two arrays of length n, must remove n/2 from each
2
Optimal Removal
Remove duplicates and minimize overlap between arrays
3
Final Set
Combine remaining elements into a set for maximum size
Key Takeaway
🎯 Key Insight: Categorize elements into unique and common groups, then greedily select to minimize overlap
Asked in
Meta 35 Google 28 Amazon 22
23.5K Views
Medium Frequency
~25 min Avg. Time
890 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