Python 1481.py
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
freq = defaultdict(int)
for a in arr:
freq[a] += 1
next = sorted(freq.values(), reverse = True)
while k > 0:
k -= next.pop()
return len(next) if k == 0 else len(next) + 1
Difficulty
and has an acceptance rate of about 64% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Greedy
- Hash Table
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that determines the smallest possible count of distinct integers remaining in an array after exactly k elements have been removed. It builds a frequency map, orders the frequencies, and then greedily discards whole groups of identical numbers starting from the least frequent ones. The final count is derived from the remaining groups, with a special adjustment when the removal budget is exhausted in the middle of a group.
Key Steps
The algorithm can be broken down into three logical phases. Each phase is illustrated with the corresponding excerpt from the source.
Frequency accumulation The method creates a dictionary that records how many times each integer appears in the input list.
freq = defaultdict(int)
for a in arr:
freq[a] += 1
Ordering of frequencies
All frequency values are extracted, sorted in descending order, and stored in a list named next. The descending order is intentional because the subsequent pop operation removes elements from the end of the list, which corresponds to the smallest frequencies.
next = sorted(freq.values(), reverse=True)
Greedy removal loop
While there is still a removal budget (k > 0), the algorithm removes the smallest remaining group by popping the last element of next and subtracting its size from k. This loop continues until the budget is exhausted or the list becomes empty.
while k > 0:
k -= next.pop()
Result computation
After the loop, the method returns the number of groups left in next. If k has reached exactly zero, the count is simply len(next). If k became negative, it indicates that the last pop removed more elements than the remaining budget, meaning a partially removed group still contributes one distinct integer to the final count. In that case the result is len(next) + 1.
return len(next) if k == 0 else len(next) + 1
Edge Cases Handled
The code gracefully addresses several boundary conditions without additional checks.
When the input array is empty, the frequency map is empty, the sorted list next is empty, and the loop body never executes. The return expression yields 0, correctly indicating no distinct integers remain.
If the removal budget k is zero, the while-loop is skipped entirely. The method returns the total number of distinct values originally present, as len(next) reflects the full set of frequencies.
When k exceeds the total number of elements in the array, the loop continues until next is emptied. At that point k is still positive, but the pop operation cannot be performed further. The return expression evaluates to len(next) + 1, which simplifies to 1. This outcome reflects that after removing all possible elements, at most one distinct integer could remain (the partially removed group scenario).
If k exactly matches the sum of the smallest frequencies removed, the loop ends with k equal to zero. The method returns len(next), representing the distinct integers that were not touched by the removal process.
When k becomes negative after subtracting a frequency larger than the remaining budget, the method adds one to the length of next. This adjustment accounts for the fact that a group was only partially eliminated, leaving a single representative of that integer in the final array.
Performance Optimizations
The implementation incorporates several choices that keep the execution efficient.
The use of defaultdict(int) eliminates the need for explicit existence checks when incrementing counts, providing constant-time updates for each element in the input list.
Sorting the frequency values once, rather than repeatedly searching for the smallest group, reduces the overall work to a single O(n log n) operation (where n is the number of distinct values). After sorting, the algorithm relies on list.pop() to remove the smallest frequency in constant time, avoiding the overhead of more complex data structures such as heaps.
By operating directly on the list of frequencies rather than on the original array, the method minimizes memory usage to a size proportional to the number of unique integers, not the total number of elements.
The final conditional expression computes the answer in constant time, using only the length of the remaining list and the sign of k. This avoids any additional traversal or counting steps.
ELI5 - Simplified Explanation
Imagine you have a big treasure box full of colorful plastic shapes like triangles, squares, and circles. Some shapes have lots of friends, and some shapes are all alone. The goal is to take away a certain number of shapes from the box, but you want to try to make as many different types of shapes disappear completely as possible.
First, the computer looks through all the shapes in the box and keeps a count of how many of each kind there are. If you have five triangles, it writes down that the triangle group has five. If you have two circles, it writes down that the circles have two.
Next, it puts those counts in a line. It decides to look at the shapes that have the fewest friends first, because it is much easier to make those disappear. The computer starts taking away the shapes that appear the least amount of times. It keeps picking up the group with the smallest number of shapes and removing them from the box until the number of shapes picked equals the amount you were asked to remove.
Once the work is finished, the computer counts how many different types of shapes are left in the box. If a type of shape was completely emptied out, it does not count that one anymore, so only the ones remaining are counted.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| muhammadfarhankt | Go | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| muhammadfarhankt | Go | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1248: Count Number of Nice Subarrays
- problem 1358: Number of Substrings Containing All Three Characters
- problem 1371: Find the Longest Substring Containing Vowels in Even Counts
- problem 1410: HTML Entity Parser
- problem 1600: Throne Inheritance
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality