LeetCode 1207. Unique Number of Occurrences

Algo.Monster
2 min readJan 31, 2023

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

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
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
# Create a dictionary to store the frequency of each number in the array
frequency_dict = {}

# Iterate through the array and count the frequency of each number
for num in arr:
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1

# Create a set to store the frequency of each number in the array
frequency_set = set(frequency_dict.values())

# Return True if the length of the frequency set is equal to the length of the frequency dictionary, or False otherwise
return len(frequency_set) == len(frequency_dict)

We start by creating a dictionary frequency_dict to store the frequency of each number in the array. We then iterate through the input array arr and count the frequency of each number. If the number is already in the frequency_dict, we increment its frequency. If the number is not in the frequency_dict, we add it and set its frequency to 1.

Next, we create a set frequency_set to store the frequency of each number in the array. The reason we use a set is to check if there are any duplicate frequencies. If there are duplicate frequencies, the length of the set will be less than the length of the dictionary.

Finally, we return True if the length of the frequency set is equal to the length of the frequency dictionary, or False otherwise.

The time complexity of this solution is O(n), where n is the length of the input array arr. This is because we need to iterate through the entire array to count the frequency of each number and then check if the frequency of each number is unique.

The space complexity of this solution is O(n), where n is the length of the input array arr. This is because we need to store the frequency of each number in a dictionary, which will take up O(n) space. Additionally, we also need to store the frequency of each number in a set, which will also take up O(n) space.

--

--

Algo.Monster

Master the Coding Interview Without Endless Grind. Take the 5-minute quiz: https://algo.monster/evaluator