1207. Unique Number of Occurrences

1207. Unique Number of Occurrences

Problem Solving - Day 60

ยท

3 min read

Hello, reader ๐Ÿ‘‹๐Ÿฝ ! Welcome to day 60 of the series on Problem Solving. Through this series, I aim to pick up at least one question everyday and share my approach for solving it.

Today, I will be picking up LeetCode's daily challenge problem: 1207. Unique Number of Occurrences.


๐Ÿค” Problem Statement

  • Given an array of integers arr, return true if the number of occurrences of each value in the array is unique, or false otherwise.

  • E.g.:

    • arr = [1,2,2,1,1,3] => true

    • arr = [1,2] => false


๐Ÿ’ฌ Thought Process - Hash Map + Set

  • This problem is pretty straightforward. If you've solved questions to count occurrences of values

  • Instead of thinking this as a single question, we'll split and think of this as into two separate problems:

    • Find the occurrence of every number in the array

    • Check if all the occurrences are same or different

  • To find the occurrences of every number in the array, we can traverse through the array and save the count of individual numbers in a map as key value pairs value, count.

  • Since we need to find if all the elements are unique, we can use a set for this.

  • Once we have found the count of every number in the array, we then traverse through all the count.

  • We add every count in a set and if this operation returns false, that means the set already contains this value.

  • If in case we complete traversing every value in the array, that means there was no duplicate count and we return true.

๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ป Solution - Hash Map + Set

  • Below is the code for the approach using hash map and array.
class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> occurrences = new HashMap();

        for(int num: arr) {
            occurrences.put(num, 
                occurrences.getOrDefault(num, 0) + 1);
        }

        Set<Integer> uniqueOccurrences = new HashSet<>();
        for(int count: occurrences.values()) {
            uniqueOccurrences.add(count);
        }

        return (uniqueOccurrences.size() == occurrences.size());
    }
}
Time Complexity: O(n)
  - n = number of elements in the array
    - We traverse all the elements in the array at least once
Space Complexity: O(n)
  - n = number of elements in the array
    - We require a map to hold occurrences of number
    - in the worst case all n numbers are different


Conclusion

That's a wrap for today's problem. If you liked my explanation then please do drop a like/ comment. Also, please correct me if I've made any mistakes or if you want me to improve something!

Thank you for reading!