Python 1748.py
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
freq = defaultdict(int)
for i in nums:
freq[i] += 1
result = 0
for i in freq:
if freq[i] == 1:
result += i
return result
Difficulty
and has an acceptance rate of about 80% (300k+ submissions).
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 class Solution with a method sumOfUnique that receives a list of integers and returns the sum of the elements that appear exactly once in the input. The algorithm proceeds in two distinct phases: first it records the occurrence count of each integer, then it aggregates the values whose count equals one.
Building the Frequency Table
The method begins by creating a defaultdict of integers named freq. This container automatically supplies a default value of zero for any new key, allowing the code to increment counts without explicit existence checks.
freq = defaultdict(int)
for i in nums:
freq[i] += 1
During the single traversal of nums, each element i is used as a key in freq, and its associated count is increased by one. This step captures the complete frequency distribution of the input list.
Summing the Unique Elements
After the frequency table is populated, the method iterates over the keys of freq. For each key, it checks whether the recorded count is exactly one. If the condition holds, the key itself (the integer value) is added to an accumulator variable result.
result = 0
for i in freq:
if freq[i] == 1:
result += i
When the loop finishes, result holds the sum of all integers that occurred a single time in the original list.
Returning the Computed Sum
The final statement simply returns the accumulated sum to the caller.
return result
Edge Cases Handled
When the input list is empty, the frequency table remains empty, the summation loop does not execute, and the method returns the initial value of result, which is zero. This correctly reflects that there are no unique elements to sum.
If every element in the list appears more than once, the condition freq[i] == 1 never becomes true, leaving result unchanged at zero. The method therefore returns zero, indicating that no unique values exist.
When all elements are distinct, each key in freq has a count of one, so the summation loop adds every element to result. The returned value is the total sum of the original list, matching the expected behavior.
The algorithm also accommodates negative integers and large magnitude values because it treats each integer uniformly as a dictionary key and performs arithmetic using Python’s arbitrary-precision integer type.
Performance Optimizations Observed
The use of defaultdict(int) eliminates the need for explicit key existence checks, reducing overhead in the frequency-building phase. By separating the counting and summation into two passes-first over the input list, then over the distinct keys-the implementation avoids repeated scanning of the original data, ensuring that each element contributes to the work only once per phase.
Iterating over freq rather than the original list for the summation step means the second loop processes at most the number of unique values, which can be substantially smaller than the length of nums when many duplicates exist. This selective iteration reduces unnecessary arithmetic operations.
Overall, the design leverages Python’s built-in dictionary hashing for constant-time updates and lookups, providing an efficient solution for the problem at hand.
ELI5 - Simplified Explanation
Imagine you have a big pile of colorful building blocks and you want to find the ones that are special because they are the only ones of their color. You start by going through the whole pile and making a little tally sheet to keep track of how many blocks you have for every color. You look at one block, check your sheet, and add a mark for that color so you can remember exactly how many you have altogether.
Once you finish counting all the blocks and your tally sheet is complete, you look over the list one more time. You look for any color that has exactly one mark on your paper. If you find a color with just one block, you keep that block to put in a special box. You do this for every single color on your list. By the end, the special box will hold only those unique blocks, and you can add up the numbers on them to see what you found.
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 | PHP | Rust | TS | |||||
| Progiez | C++ | Python | Java | |||||||||
| github | black-shadows | C++ | ||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 455: Assign Cookies
- problem 500: Keyboard Row
- problem 575: Distribute Candies
- problem 1009: Complement of Base 10 Integer
- problem 1071: Greatest Common Divisor of Strings
- problem 1299: Replace Elements with Greatest Element on Right Side
- problem 1979: Find Greatest Common Divisor of Array
- problem 2148: Count Elements With Strictly Smaller and Greater Elements
- problem 2309: Greatest English Letter in Upper and Lower Case
- problem 216: Combination Sum III
- problem 229: Majority Element II
- problem 373: Find K Pairs with Smallest Sums
- problem 470: Implement Rand10() Using Rand7()
- problem 503: Next Greater Element II
- problem 556: Next Greater Element III
- problem 622: Design Circular Queue
- problem 1262: Greatest Sum Divisible by Three
- problem 2657: Find the Prefix Common Array of Two Arrays
- problem 2807: Insert Greatest Common Divisors in Linked List
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