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] <= 1000In this approach, we will first traverse the array to count the occurrences of each element using a hash map. Then, we will use a set to check if these occurrences are unique. If the size of the set matches the size of the occurrence counts, it implies all occurrences are unique.
In the C implementation, we use an array count to store the frequency of each element adjusted by 1000 to handle negative indices. The hash array is used to ensure all frequencies are unique.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), since we're using fixed-size arrays.
This alternative approach starts by counting occurrences just like the first one. After that, it stores these counts in a list, sorts the list, and then checks for any consecutive equal elements, which would indicate duplicate occurrences.
In the C implementation using sorting, we use qsort to sort the frequency array and then check if any consecutive elements are equal.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(1), since we work within fixed-sized arrays.
| Approach | Complexity |
|---|---|
| Hash Map and Set | Time Complexity: O(n), where n is the length of the array. |
| Sorting and Comparison | Time Complexity: O(n log n), due to sorting. |
Apple Coding Interview Question! | Leetcode 1207 - Unique Number of Occurrences • Greg Hogg • 105,386 views views
Watch 9 more video solutions →Practice Unique Number of Occurrences with our built-in code editor and test cases.
Practice on FleetCode