Sum of Unique Elements: Frequency Counting Pattern
LeetCode Sum of Unique Elements asks a simple question: given an integer array nums, return the sum of all the elements that appear exactly once. If a value shows up more than once, you skip it entirely.
For example, given nums = [1, 2, 3, 2], the answer is 4. The value 2 appears twice, so you ignore it. The values 1 and 3 each appear exactly once, so you sum them: 1 + 3 = 4.
Why this problem matters
Sum of Unique Elements is an easy problem, but it teaches one of the most reusable patterns in all of algorithm interviews: frequency counting with a hash map. The idea is simple. You scan through a collection, count how many times each element appears, and then use those counts to answer the question.
This same pattern shows up in dozens of problems at every difficulty level. Group Anagrams uses it to bucket strings by character frequency. Top K Frequent Elements uses it to rank items by count. Majority Element uses it to find the most common value. Once you internalize frequency counting, you will recognize it instantly across a wide range of problems.
What makes this particular problem a good starting point is that it strips the pattern down to its bare minimum. There is no sorting, no grouping, no secondary data structure. You count, you filter, you sum. That simplicity lets you focus entirely on the counting step itself.
The key insight
You need to know how many times each element appears before you can decide which ones to include in the sum. Trying to do it in one pass without counting first would mean you might add a value and then realize later it was a duplicate, forcing you to subtract it back out. That is messy and error-prone.
The cleaner approach: make one pass to count everything, then make a second pass (over the counts) to sum only the unique ones. A Counter or dictionary makes the first pass trivial, and iterating over its entries makes the second pass equally simple.
The solution
from collections import Counter
def sum_of_unique(nums: list[int]) -> int:
counts = Counter(nums)
return sum(val for val, cnt in counts.items() if cnt == 1)
This is the entire solution. Counter(nums) builds a dictionary mapping each element to its frequency. Then the generator expression iterates over every key-value pair and sums only the keys where the count is exactly 1.
Python's Counter is a subclass of dict that is purpose-built for counting. It takes any iterable and returns a mapping of element to count. You could also use a plain dictionary with a manual counting loop, but Counter does the same thing in one line.
Counter is your go-to tool for any problem that asks about frequencies, duplicates, or counts. It builds the frequency map in O(n) time and gives you O(1) lookups by element.
Visual walkthrough
Step 1: Walk the array and count each element
Iterate through nums, incrementing a counter for each value.
Step 2: The frequency map after counting
Element 2 has count 2. Elements 1 and 3 each have count 1.
Step 3: Filter elements where count equals 1
Skip element 2 (count is 2). Keep elements 1 and 3 (count is 1).
Step 4: Sum the unique elements
1 + 3 = 4. That is the final answer.
That is the full algorithm. Build the frequency map, check each entry, and sum the ones with count equal to 1. No sorting needed, no nested loops, no special cases.
Complexity analysis
| Approach | Time | Space |
|---|---|---|
| Frequency Counter | O(n) | O(n) |
Time: You iterate through the array once to build the frequency map, then iterate through the map entries to compute the sum. Both passes are O(n), so the total is O(n).
Space: The frequency map stores at most n entries (if every element is distinct), so space is O(n). In practice, it is often much smaller because duplicate elements share a single entry.
The building blocks
1. Frequency counting with hash map
The first building block is constructing the count map itself. You scan through the input and increment a counter for each element.
from collections import Counter
counts = Counter(nums)
Or, if you want to see the manual version:
counts = {}
for num in nums:
counts[num] = counts.get(num, 0) + 1
Both produce the same result. The manual version is useful when you need to customize the counting logic, but Counter is the standard tool.
2. Filtering by count
Once you have the frequency map, you iterate over its entries and apply a condition. In this case, the condition is "count equals 1."
total = sum(val for val, cnt in counts.items() if cnt == 1)
This filtering step is the second half of almost every frequency counting problem. The condition changes (count equals k, count greater than n // 2, count is maximal), but the structure stays the same: iterate over the map and apply your filter.
Edge cases
- All elements are unique: Every element has count 1, so the answer is the sum of the entire array.
- All elements are duplicates: Every element has count greater than 1, so the answer is 0.
- Single element: The array has one element, and it appears exactly once. The answer is that element.
- Large duplicate groups: An element might appear 50 times. It still gets skipped because its count is not 1.
- Negative numbers: The problem works with any integers. Negative values with count 1 still get summed.
From understanding to recall
Reading through this solution probably feels obvious. Count the elements, filter by count, sum the result. But "obvious when reading" and "automatic when solving" are two very different things. A week from now, when you see a problem that asks about element frequencies in a different context, you want the frequency counter pattern to fire instantly without any deliberation.
That is where active recall matters. Instead of just reading the Counter approach, you practice writing it from scratch at increasing intervals. After a few rounds of spaced repetition, the pattern is in your muscle memory. You see "count occurrences" and your fingers are already typing Counter(nums) before your conscious mind catches up.
Related posts
- Two Sum - The classic hash map problem for complement lookup
- Contains Duplicate - Uses a hash set to detect duplicates
- Group Anagrams - Groups elements by a hash map key
Sum of Unique Elements is as clean as frequency counting gets. One data structure, one filter, one sum. But the building blocks you practice here, counting with a hash map and filtering by count, are the exact same pieces you will need for medium and hard problems that layer additional complexity on top. Start simple, build the habit, and the harder problems become a matter of composition rather than invention.