Program to check occurrences of every value is unique or not in Python


Suppose we have a list of numbers nums (positive or negative), we have to check whether the number of occurrences of every value in the array is unique or not.

So, if the input is like nums = [6, 4, 2, 9, 4, 2, 2, 9, 9, 9], then the output will be True, as there is 1 occurrence of 6, 2 occurrences of 4, 3 occurrences of 2, and 4 occurrences of 9. So all number of occurrences are unique.

To solve this, we will follow these steps −

  • num_counts := a new map where all values and number of occurrences of that value is stored

  • occurrences := list of all values of num_counts

  • return True when size of occurrences is same as number of unique elements in occurrences, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import Counter
class Solution:
   def solve(self, nums):
      num_counts = dict(Counter(nums))
      occurrences = num_counts.values()
      return len(occurrences) == len(set(occurrences))
ob = Solution()
nums = [6, 4, 2, 9, 4, 2, 2, 9, 9, 9]
print(ob.solve(nums))

Input

[6, 4, 2, 9, 4, 2, 2, 9, 9, 9]

Output

True

Updated on: 21-Oct-2020

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements