Leetcode 1207. Unique Number of Occurrences
Given an array of integers arr
, write a function that returns true
if the number of occurrences of each value in the array is unique, or false
otherwise.
arr = [1,2,2,1,1,3]
true
Explanation: The value 1 has 3 occurrences, value 2 has 2 occurrences, and value 3 has 1 occurrence. No two values have the same number of occurrences.arr = [1,2]
false
Explanation: Both values 1 and 2 occur exactly once.arr = [-3,0,1,-3,1,1,1,-3,10,0]
true
1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
HashMap
to count the occurrences of each number in the array.HashSet
to store the counts of occurrences.HashSet
of occurrences is the same as the size of the HashMap
of elements, it means all counts are unique.HashMap<Integer, Integer>
to count the occurrences of each element in the array.HashMap
.HashSet<Integer>
to store the values of these counts.HashMap
and add them to the HashSet
.HashMap
and the HashSet
. If they are equal, return true
, else return false
.import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class UniqueNumberOccurrences {
public boolean uniqueOccurrences(int[] arr) {
// Step 1: Count occurrences
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : arr) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
// Step 2: Store counts in a HashSet
HashSet<Integer> countSet = new HashSet<>();
for (int count : countMap.values()) {
countSet.add(count);
}
// Step 3: Check if countSet size is the same as countMap size
return countSet.size() == countMap.size();
}
public static void main(String[] args) {
UniqueNumberOccurrences solution = new UniqueNumberOccurrences();
// Test case 1
int[] arr1 = {1, 2, 2, 1, 1, 3};
System.out.println(solution.uniqueOccurrences(arr1)); // true
// Test case 2
int[] arr2 = {1, 2};
System.out.println(solution.uniqueOccurrences(arr2)); // false
// Test case 3
int[] arr3 = {-3, 0, 1, -3, 1, 1, 1, -3, 10, 0};
System.out.println(solution.uniqueOccurrences(arr3)); // true
}
}
The time complexity of this approach is O(n), where n is the number of elements in the array. This is because:
HashMap
to add the counts to the HashSet
, which is also O(n).Thus, the overall time complexity is O(n).
The space complexity is O(n) due to the usage of the HashMap
and the HashSet
, which can both contain at most n elements in the worst case.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?