Unique Number of Occurrences - Problem

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

In other words: No two different values should have the same frequency count.

Input & Output

Example 1 — All Unique Frequencies
$ Input: arr = [1,2,2,1,1,3]
Output: true
💡 Note: Element 1 appears 3 times, element 2 appears 2 times, element 3 appears 1 time. Frequencies [3,2,1] are all unique.
Example 2 — Duplicate Frequencies
$ Input: arr = [1,2]
Output: false
💡 Note: Element 1 appears 1 time, element 2 appears 1 time. Both have frequency 1, so frequencies [1,1] are not unique.
Example 3 — Single Element
$ Input: arr = [5]
Output: true
💡 Note: Only one element with frequency 1. Since there's only one frequency count, it's trivially unique.

Constraints

  • 1 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000

Visualization

Tap to expand
Unique Number of Occurrences Single Pass Optimization Approach INPUT arr = [1, 2, 2, 1, 1, 3] 1 2 2 1 1 3 [0] [1] [2] [3] [4] [5] Value Counts: 1: 3x 2: 2x 3: 1x Frequency Visualization: 1: (3) 2: (2) 3: (1) ALGORITHM STEPS 1 Count Frequencies Use HashMap to count each value's occurrences 2 Extract Counts Get all frequency values: [3, 2, 1] 3 Check Uniqueness Add counts to HashSet to detect duplicates 4 Compare Sizes If Set.size == Map.size then all counts unique HashSet of Counts: 3 2 1 size=3 FINAL RESULT true All counts are unique! Verification: Frequency counts: [3, 2, 1] 3 appears: 1 time -- OK 2 appears: 1 time -- OK 1 appears: 1 time -- OK Why TRUE? Map size: 3 values Set size: 3 unique counts 3 == 3 : MATCH! No duplicate frequencies Key Insight: Use a HashMap to count occurrences of each value, then use a HashSet to check if all counts are unique. If the Set size equals the Map size, no two values share the same frequency. Time: O(n), Space: O(n). TutorialsPoint - Unique Number of Occurrences | Single Pass Optimization
Asked in
Amazon 15 Microsoft 12
178.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen