problemeasyalgorithmsleetcode-1207leetcode 1207leetcode1207

Unique Number of Occurrences

EasyUpdated: Aug 2, 2025
Practice on:

Problem

Given an array of integers arr, return true _if the number of occurrences of each value in the array isunique or _false otherwise.

Examples

Example 1

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation:  The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2

Input: arr = [1,2]
Output: false

Example 3

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

Constraints

  • 1 <= arr.length <= 1000
  • -1000 <= arr[i] <= 1000

Solution

Method 1 – Hash Map and Set

Intuition

Count the occurrences of each value, then check if all occurrence counts are unique using a set.

Approach

  1. Count the frequency of each value in the array.
  2. Check if the set of frequencies has the same size as the list of frequencies.

Code

Java
import java.util.*;
class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int x : arr) freq.put(x, freq.getOrDefault(x, 0) + 1);
        Set<Integer> seen = new HashSet<>(freq.values());
        return seen.size() == freq.size();
    }
}
Python
def uniqueOccurrences(arr):
    from collections import Counter
    freq = Counter(arr)
    return len(set(freq.values())) == len(freq)

Complexity

  • ⏰ Time complexity: O(n) — One pass to count, one pass to check uniqueness.
  • 🧺 Space complexity: O(n) — For hash maps and sets.

Comments