Unique Number of Occurrences

Given an integer array arr, please help to count the occurrences of each number in the array.

Return true if the occurrences of each number are unique, otherwise return false.

Example

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: In this array, 1 appears 3 times, 2 appears 2 times, and 3 appears only 1 time. There are no two numbers with the same number of occurrences.
Input: arr = [1,2]
Output: false
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

Solution

/**
 * @param {number[]} arr
 * @return {boolean}
 */
var uniqueOccurrences = function(arr) {
    var hashTable = Object.create(null);
    arr.forEach(v => {
        if(hashTable[v] === void 0) hashTable[v] = 1;
        else ++hashTable[v];
    })
    var keys = Object.keys(hashTable);
    var values = Object.values(hashTable);
    return keys.length === [...new Set(values)].length;
};

Approach

Use a hash table to record the occurrences of each number, then use a Set to handle the occurrences, and finally compare the length of the hash table with the length of the Set. First, define a hash table, in this case, we use a regular object in JavaScript, but Map object in Js can also be used as a key-value hash table solution. After that, iterate through the array, if the key is undefined, set the value of this key in the hash table to 1, otherwise increment the value. Then get all the keys and values from the object, use a Set to deduplicate the values array, and then compare the length of the deduplicated array with the length of the keys array, and return the result.

Daily Topic

https://github.com/WindrunnerMax/EveryDay

Reference

https://leetcode-cn.com/problems/unique-number-of-occurrences/