Python 1207.py
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
freq = defaultdict(int)
for a in arr:
freq[a] += 1
return len(freq.values()) == len(set(freq.values()))
Difficulty
and has an acceptance rate of about 78% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
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 solves the problem of determining whether the number of occurrences of each distinct element in an integer list are all unique. It does so by constructing a frequency map for the input list and then verifying that the collection of frequency counts contains no duplicates. The solution is compact, leverages Python’s standard library collections, and follows a straightforward procedural flow.
Key Steps
The algorithm can be divided into three logical phases: initialization of a counting container, population of that container with occurrence data, and a final uniqueness test.
Initialization
freq = defaultdict(int)
A defaultdict with int as the default factory is created. This choice eliminates the need for explicit key existence checks when incrementing counts, because any missing key is automatically initialized to zero.
Population
for a in arr:
freq[a] += 1
The code iterates over each element a in the input list arr. For each element, the corresponding entry in freq is incremented. Because freq is a defaultdict, the first encounter of any value automatically creates a new entry with a count of zero before the increment, ensuring correct tallying without additional conditional logic.
Uniqueness Test
return len(freq.values()) == len(set(freq.values()))
After the counting phase, the method extracts the collection of frequency values. Converting this collection to a set removes any duplicate counts. By comparing the size of the original values view with the size of the deduplicated set, the code determines whether all frequencies are distinct. If the sizes match, every count appears exactly once, and the function returns True; otherwise it returns False.
Edge Cases Handled
The implementation gracefully handles several edge conditions without special-case code. When the input list is empty, the frequency map remains empty, and both len(freq.values()) and len(set(freq.values())) evaluate to zero, resulting in a True outcome, which aligns with the definition that an empty collection trivially satisfies the uniqueness property. If the list contains a single repeated value, the frequency map will have a single entry with a count equal to the length of the list; the comparison of lengths will succeed because there is only one frequency value. The algorithm also works correctly for lists containing negative integers, zero, or large integer values, because the counting mechanism treats keys as opaque hashable objects. Duplicate values that produce identical frequencies are correctly identified as a violation of the uniqueness condition, as the set conversion will collapse those duplicates, causing the length comparison to fail.
Performance Optimizations
The code benefits from a few implicit optimizations. Using defaultdict(int) removes the overhead of repeatedly checking for key presence, which would otherwise require a conditional branch for each element. The single pass over the input list ensures that each element contributes to the frequency map exactly once, avoiding redundant work. The final uniqueness check leverages Python’s built-in set constructor, which is implemented in C and provides fast hashing and insertion for the frequency values. By performing the comparison of lengths rather than iterating through the values to detect duplicates manually, the solution minimizes Python-level loop overhead. Overall, the approach achieves the desired result with minimal code and efficient use of the language’s high-performance data structures.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of different colored building blocks. Some colors appear many times, and some colors appear only once. This code helps figure out if every color has a different number of friends.
First, the computer looks at every block in the bucket one by one. It keeps a little notepad to count how many times each color shows up. If it sees a red block, it adds a mark next to the word red on the notepad. It does this until every single block has been counted.
After all the blocks are counted, the computer looks at the numbers on the notepad, like how many reds there are and how many blues there are. It writes these counts down on a piece of paper.
Next, it puts those count numbers into a special bag that only keeps one of each number. For example, if there are three red blocks and three green blocks, the bag sees two threes but only keeps one.
Finally, the computer compares the pile of counts to the special bag. If the pile and the bag have the exact same number of items, that means every color had a totally unique number of friends. If the numbers are different, it means some colors shared the same amount.
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 | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| pruthvikp | Python | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| pruthvikp | Python | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1897: Redistribute Characters to Make All Strings Equal
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
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