#3002
Maximum Size of a Set After Removals
MediumArrayHash TableGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a greedy strategy to maximize the unique elements in the resulting set by counting the occurrences of elements in both arrays and strategically choosing which elements to keep.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each element in both nums1 and nums2.
- 2Step 2: Create a set of unique elements from both arrays.
- 3Step 3: Calculate the maximum possible size of the set by keeping unique elements while ensuring we only keep n/2 elements from each array.
solution.py9 lines
1# Full working Python code
2from collections import Counter
3
4def maxSetSize(nums1, nums2):
5 count1 = Counter(nums1)
6 count2 = Counter(nums2)
7 unique_elements = set(nums1) | set(nums2)
8 max_size = min(len(unique_elements), len(nums1) // 2 + len(nums2) // 2)
9 return max_sizeℹ
Complexity note: The complexity is O(n) because we only pass through the arrays a couple of times to count elements and create a set of unique values.
- 1Maximizing unique elements requires careful selection of which elements to keep.
- 2Using frequency counts helps in determining the best strategy for removals.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.