715906. Unique Number of Occurrences

Easy

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:

  1. Create an empty hashmap freqMap to store the frequency of each element in the array.
  2. 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.
  3. Create an empty set uniqueSet to store the unique elements that have a frequency of 1.
  4. Iterate through freqMap, and for each element:
    • Check if its frequency is equal to 1. If so, add it to uniqueSet.
  5. 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

View on GeeksforGeeks
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();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.