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 Removals INPUT nums1 (n=4) 1 2 3 4 nums2 (n=4) 3 4 5 6 Remove n/2 = 2 from each Keep n/2 = 2 from each Unique Elements: nums1: {1,2,3,4} nums2: {3,4,5,6} Common: {3,4} Only in nums1: {1,2} Only in nums2: {5,6} ALGORITHM STEPS 1 Find Unique Sets Convert arrays to sets 2 Categorize Elements Only1, Only2, Common 3 Greedy Selection Prioritize unique elements 4 Calculate Max Size min(total unique, n) Calculation: only1 = {1,2}, cnt=2 only2 = {5,6}, cnt=2 common = {3,4}, cnt=2 keep1 = min(2,2) = 2 keep2 = min(2,2) = 2 FINAL RESULT Optimal Selection: From nums1: keep {1, 2} 1 2 From nums2: keep {5, 6} 5 6 Final Set s: {1, 2, 5, 6} OUTPUT 4 Key Insight: Greedy strategy: Prioritize elements unique to each array over common elements. Take min(unique_only, n/2) from each array, then fill remaining slots with common elements. Result = min(total_unique_elements, n) where n is the combined size we can keep. TutorialsPoint - Maximum Size of a Set After Removals | Optimal Greedy Strategy
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