Solution: Unique Number of Occurrences

Let's solve the Unique Number of Occurrences problem using the Hash Maps pattern.

Statement

Given an array of integers nums, return TRUE if each value in the array has a unique number of occurrences; otherwise, return FALSE.

Constraints:

  • 11<= nums.length <=10001000

  • 1000-1000 <= nums[i] <= 10001000

Solution

The algorithm checks if there is a unique number of occurrences of each element by using a hash map and a hash set. First, for each element of the nums array, put the element in the hash map if it does not already exist in the hash map; otherwise, increment its count. Second, put all the elements' frequencies (counts) in a hash set. Finally, the algorithm will return TRUE if the count of the hash map and the hash set is the same and FALSE otherwise.

The algorithm to solve this problem is as follows:

  • Initialize a hash map and a hash set.

  • Iterate over the nums array, and for each element:

    • If the element is not already in the hash map, put the element in the hash map as a key and 11 as the value.

    • Otherwise, if the element already exists in the hash map, increment that element's value by 11.

  • After the loop terminates, iterate over the hash map and store all values of its elements to the hash set.

  • Because the hash set does not allow duplicates and stores only unique values, if the lengths of the hash map and the hash set are the same, it means that there is no duplicate frequency of an element in the hash map. In this case, return TRUE; otherwise, return FALSE.

Look at the following illustration to get a better understanding of the solution:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.