algoadvance

Given an array of integers arr, you need to determine if the number of occurrences of each value in the array is unique.

More precisely, for an array arr, we have to check if the occurrences of each element in the array are all different. If the occurrences are unique, return True, otherwise return False.

Clarifying Questions

  1. What is the range of values in the array?
    • The values can be any integer (both positive and negative).
  2. What is the maximum and minimum length of the array?
    • The array can have a length ranging from 1 to 1000.
  3. Can the array be empty?
    • Based on the problem statement, no, the array will have at least one element.

Strategy

  1. Count Occurrences:
    • Use a dictionary to count the occurrences of each element in the array.
  2. Check for Unique Occurrences:
    • Store the occurrences in a set. Since sets do not allow duplicates, if the length of the set is equal to the number of unique elements in the original dictionary, then all occurrences are unique.
    • Otherwise, there are repeated occurrences.

Code

Here is the complete Python code for the problem:

from collections import Counter

def uniqueOccurrences(arr):
    # Step 1: Count occurrences of each element
    element_count = Counter(arr)
    
    # Step 2: Extract the occurrences
    occurrences = list(element_count.values())
    
    # Step 3: Check for unique occurrences
    return len(occurrences) == len(set(occurrences))

# Example usage:
# arr = [1,2,2,1,1,3]
# The output should be True because the counts are {1: 3, 2: 2, 3: 1} and they are all unique.
print(uniqueOccurrences([1, 2, 2, 1, 1, 3]))  # Output: True

Time Complexity

This approach ensures that the problem is solved efficiently even for the maximum constraint size.

Try our interview co-pilot at AlgoAdvance.com