Problem 1207

Abstract / Summary

Check if the count of each number in a list is different from the count of every other number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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()))
7 lines | 221 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.35 | σ = 0.92

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
38 links | 27 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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