715906. Unique Number of Occurrences
Unique Number of Occurrences
Slug: unique-frequencies-of-not Difficulty: Easy Id: 715906 Topic Tags: set, Sorting, Map Company Tags: PayPal, Bloomberg, Adobe, Google, Amazon, Apple
Summary
Given an array of integers nums, return the number of unique values that have only one occurrence. In other words, count the number of elements that appear exactly once in the array.
This problem involves using a combination of map and set data structures to solve it efficiently. We'll use a hashmap to store the frequency of each element and then iterate over the map to find the ones with a frequency of 1.
Detailed Explanation
To solve this problem, we can follow these steps:
- Create an empty hashmap
freqMapto store the frequency of each element in the array. - Iterate through the array, and for each element:
- Check if it's already present in
freqMap. If not, add it with a frequency of 1. - If it is present, increment its frequency by 1.
- Check if it's already present in
- Create an empty set
uniqueSetto store the unique elements that have a frequency of 1. - Iterate through
freqMap, and for each element:- Check if its frequency is equal to 1. If so, add it to
uniqueSet.
- Check if its frequency is equal to 1. If so, add it to
- Return the size of
uniqueSet.
Here's a step-by-step breakdown:
freqMap = {}
for num in nums:
if num not in freqMap:
freqMap[num] = 1
else:
freqMap[num] += 1
uniqueSet = set()
for key, value in freqMap.items():
if value == 1:
uniqueSet.add(key)
return len(uniqueSet)
The time complexity of this solution is O(n), where n is the length of the input array. This is because we're iterating through the array twice and the hashmap operations (insertion and lookup) take constant time.
The space complexity is also O(n), as in the worst case, every element in the array could be unique and stored in the hashmap.
Optimized Solutions
Java
public int findSingle(int[] nums) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
Set<Integer> uniqueSet = new HashSet<>();
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
if (entry.getValue() == 1) {
uniqueSet.add(entry.getKey());
}
}
return uniqueSet.size();
}