#1338
Reduce Array Size to The Half
MediumArrayHash TableGreedySortingHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach focuses on counting the frequency of each integer and then strategically removing the most frequent integers first. This is efficient because removing high-frequency integers reduces the array size significantly.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each integer in the array using a HashMap.
- 2Step 2: Sort the frequencies in descending order.
- 3Step 3: Iterate through the sorted frequencies, removing integers until at least half of the array is removed, counting how many integers were removed.
solution.py15 lines
1# Full working Python code
2from collections import Counter
3
4def minSetSize(arr):
5 n = len(arr)
6 half = n // 2
7 freq = Counter(arr)
8 sorted_freq = sorted(freq.values(), reverse=True)
9 removed_count = 0
10 set_size = 0
11 for count in sorted_freq:
12 removed_count += count
13 set_size += 1
14 if removed_count >= half:
15 return set_sizeℹ
Complexity note: The time complexity is O(n log n) due to the sorting step of the frequency counts, while the space complexity is O(n) for storing the frequency counts.
- 1Removing the most frequent integers first is the most effective strategy.
- 2The problem can be efficiently solved using frequency counting and sorting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.