#1207

Unique Number of Occurrences

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a hash map allows us to efficiently count occurrences in a single pass, and then we can check for uniqueness using a set, which is much faster.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a hash map to count occurrences of each number in the array.
  2. 2Step 2: Use a set to track the counts and check for duplicates.
  3. 3Step 3: If a count already exists in the set, return false; otherwise, add it to the set.
solution.py9 lines
1def uniqueOccurrences(arr):
2    from collections import Counter
3    count_map = Counter(arr)
4    counts = set()
5    for count in count_map.values():
6        if count in counts:
7            return False
8        counts.add(count)
9    return True

Complexity note: The time complexity is O(n) because we traverse the array once to count occurrences and then traverse the hash map to check for uniqueness. The space complexity is O(n) due to the hash map and set used to store counts.

  • 1Using a hash map can significantly reduce the time complexity.
  • 2Checking for uniqueness can be efficiently done using a set.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.