Coding Challenge from Leetcode - Unique Number of Occurrences!
Here is the problem and solution to a coding challenge from Leetcode.com called Unique Number of Occurrences!
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
Use a hashmap to store the frequency of each character, then use a set to check for duplicates
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
- Create a map to hold frequencies
- 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
- Create a set to use to check for duplicates
- Loop the values in the frequency map
- 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.
- Return true at the end the function (the number of occurrences IS unique if we get here)
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: