Count Unique Elements in Array
Arrays & HashingAuto-graded · 22 test casesLast updated
Identify how many values appear exactly one time in an integer array using frequency analysis.
You are given an array of integers. Your task is to determine how many distinct values have a frequency of exactly one—that is, how many numbers appear precisely once in the entire array.
Write a function that takes an array of integers and returns the count of values that occur exactly once.
Constraints
- The array length satisfies
0 ≤ len(numbers) ≤ 200,000. - Each integer is in the range
[-1,000,000,000, 1,000,000,000]. - If a value appears two or more times, it does not contribute to the count, regardless of where in the array those occurrences are located.
- An empty array should return
0. - Target an expected time complexity of
O(n).
Examples
Example 1
Input: count_unique_elements([4, 2, 1, 4, 4, 1, 3])
Output: 2
Example 2
Input: count_unique_elements([5, 5, -1, -1])
Output: 0
Hints
Hint 1
Build a complete frequency count first before deciding which values qualify—scanning left to right without tracking total occurrences can miss later duplicates.
Hint 2
A hash map (or Counter) lets you record how many times each distinct value appears in a single pass, then filter for counts equal to one.
Hint 3
The number of keys with frequency one is your answer, not the sum of the values themselves or the total number of distinct values.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is that you cannot decide whether a value qualifies while scanning the array from left to right, because a value that first appears at index 2 might repeat at index 50. The solution requires knowing the complete frequency of every value before making any decisions.
Break the problem into two distinct phases:
- Frequency counting: Make one pass through the array to build a mapping from each distinct value to its total number of occurrences.
- Filtering: Iterate over the frequency counts and tally how many of them equal exactly one.
Python's collections.Counter handles the first phase cleanly. It produces a dictionary-like object where each key is a distinct value from the array and each value is that number's frequency. The answer is simply how many entries in this map have a count of 1.
Consider the array [4, 2, 1, 4, 4, 1, 3]:
- After counting:
{4: 3, 2: 1, 1: 2, 3: 1} - Values with frequency
1:2and3 - Answer:
2
For the array [5, 5, -1, -1]:
- After counting:
{5: 2, -1: 2} - No values have frequency
1 - Answer:
0
Why It Works
Building the frequency map ensures every element is visited exactly once and increments its corresponding key. Each distinct value appears as exactly one key in the map, so when we examine the counts, we look at each distinct number once and only once—no value is counted multiple times even if it appeared many times in the input.
A value contributes to the result if and only if its final count is 1. Because we only check counts after processing the entire array, we correctly handle cases where duplicates are separated (like [1, 2, 1]), where all values repeat (like [5, 5, -1, -1]), and where the array is empty (the sum over an empty collection is 0).
The expression sum(count == 1 for count in ...) leverages Python's treatment of booleans as integers: True contributes 1 and False contributes 0.
Complexity
- Time: Expected
O(n). Constructing the counter involvesnhash table insertions or updates, each taking expected constant time. The second pass examines at mostndistinct keys (in practice, often far fewer). - Space:
O(k), wherekis the number of distinct values. In the worst case (k = n, all values distinct), this is 200,000 entries, which is manageable.
Solution Code
from collections import Counter
from typing import List
def count_unique_elements(numbers: List[int]) -> int:
return sum(count == 1 for count in Counter(numbers).values())
An alternative implementation using an explicit dictionary (useful if you need to demonstrate understanding without library helpers):
from typing import List
def count_unique_elements(numbers: List[int]) -> int:
freq = {}
for x in numbers:
freq[x] = freq.get(x, 0) + 1
result = 0
for count in freq.values():
if count == 1:
result += 1
return result
Both implementations return identical results, including 0 for an empty array.