Coding Challenge from Leetcode - Unique Number of Occurrences!

Kelvin Graddick · 1 minute read ·     
Here is the problem and solution to a coding challenge from Leetcode.com called 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.

Solution Summary


Intuition / tip


Use a hashmap to store the frequency of each character, then use a set to check for duplicates

Steps

  1. Create a map to hold frequencies
  2. Loop the input array - for each item either add it to the map with a value of 1, or increment the value if already in the map
  3. Create a set to use to check for duplicates
  4. Loop the values in the frequency map
  5. For each item check if already in the duplicates set, if so, return false (the number of occurrences IS NOT unique). If not, add the item to the duplicate set.
  6. Return true at the end the function (the number of occurrences IS unique if we get here)

    1. Time complexity


      O(n) where ’n’ is the number of characters of the input array

      Space complexity


      O(n) where ’n’ is the number of characters of the input array


      Let me know if you have any questions or see ways I could have optimized!

      Here is a video of me working through the problem:



Want to share this?