Code Logo

Unique Number of Occurrences

Published at23 Jul 2026
Easy 2 views
Like0

Given an array of integers, return true if the number of occurrences of each value in the array is unique. Return false otherwise.

First, count the frequency of each value using a hash map. Then, check if all the frequencies are unique by putting them into a hash set. If the size of the hash set equals the number of distinct values in the hash map, all frequencies are unique.

For example, arr = [1,2,2,1,1,3] has frequencies: 1 appears 3 times, 2 appears 2 times, 3 appears 1 time. All frequencies (3, 2, 1) are unique. Return true.

This problem tests understanding of both hash maps (for counting frequencies) and hash sets (for checking uniqueness). It combines two hash-based data structures in one problem.

The problem has two clear phases: counting frequencies and checking for uniqueness. The hash map handles frequency counting in O(n) time. The hash set then checks if any two values in the hash map have the same count by trying to insert each count into the set. If a count already exists in the set, the frequencies are not unique.

An empty array returns true because there are zero frequencies, which trivially means all frequencies are unique. Arrays with a single element also return true.

Example Input & Output

Example 1
Input
[1,2,2,1,1,3]
Output
true
Explanation

Freq: 1->3, 2->2, 3->1. All unique.

Example 2
Input
[1,2,2,3,3,3]
Output
true
Explanation

Freq: 1->1, 2->2, 3->3. All unique.

Example 3
Input
[1,2]
Output
false
Explanation

Freq: 1->1, 2->1. Both 1, not unique.

Algorithm Flow

Recommendation Algorithm Flow for Unique Number of Occurrences
Recommendation Algorithm Flow for Unique Number of Occurrences

Solution Approach

Count frequencies with hash map. Store counts in a hash set. Return size of set == size of map.

function solution(arr) {
  var freq = {};
  for (var i = 0; i < arr.length; i++) freq[arr[i]] = (freq[arr[i]] || 0) + 1;
  var uniq = {};
  for (var k in freq) {
    if (uniq[freq[k]]) return false;
    uniq[freq[k]] = true;
  }
  return true;
}

Time O(n), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public boolean solution(int[] arr) {
        Map<Integer,Integer> freq = new HashMap<>();
        for (int x : arr) freq.put(x, freq.getOrDefault(x, 0) + 1);
        Set<Integer> uniq = new HashSet<>(freq.values());
        return uniq.size() == freq.size();
    }
}