Count Unique Frequencies — Problem Statement & Solution Guide
Problem Description
Given a list of integers representing mineral frequencies, determine the count of distinct frequencies in the list.
Examples
Input
[1, 2, 2, 3, 3, 3]
Output
3
Explanation: Step-by-step: with input [1, 2, 2, 3, 3, 3], we count the frequency of each number. The frequency of 1 is 1, the frequency of 2 is 2, and the frequency of 3 is 3. Therefore, the count of distinct frequencies is 3.
Input
[4, 4, 4, 4]
Output
1
Explanation: Step-by-step: with input [4, 4, 4, 4], we count the frequency of each number. The frequency of 4 is 4. Therefore, the count of distinct frequencies is 1.
Constraints
- 1 <= s.length <= 10^5
- s consists of only lowercase English letters.
Optimal Approach & Strategy
The optimized approach would involve using a hash set to store unique minerals, resulting in a time complexity of O(n).
Brute Force Approach
The brute force approach would involve sorting the list of mineral frequencies and then counting the number of unique minerals by iterating through the sorted list.
Verified Code Solutions
function solution(nums) { let freq = {}; for (let num of nums) { if (freq[num]) { freq[num]++; } else { freq[num] = 1; } }; let uniqueFreq = new Set(); for (let num in freq) { uniqueFreq.add(freq[num]); }; return uniqueFreq.size; }class Solution { public: int solution(vector<int>& nums) { unordered_map<int, int> freq; for (int num : nums) { freq[num]++; } unordered_set<int> uniqueFreq; for (auto& num : freq) { uniqueFreq.insert(num.second); } return uniqueFreq.size(); } }import java.util.HashSet; import java.util.HashMap; class Solution { public int solution(int[] nums) { HashMap<Integer, Integer> freq = new HashMap<>(); for (int num : nums) { freq.put(num, freq.getOrDefault(num, 0) + 1); } HashSet<Integer> uniqueFreq = new HashSet<>(); for (int num : freq.values()) { uniqueFreq.add(num); } return uniqueFreq.size(); } }def solution(nums): freq = {}; for num in nums: if num in freq: freq[num] += 1; else: freq[num] = 1; unique_freq = set(); for num in freq: unique_freq.add(freq[num]); return len(unique_freq)function solution(nums) { let freq = {}; for (let num of nums) { if (freq[num]) { freq[num]++; } else { freq[num] = 1; } }; let uniqueFreq = new Set(); for (let num in freq) { uniqueFreq.add(freq[num]); }; return uniqueFreq.size; }Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.