- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Unique Number of Occurrences in Python
Suppose we have an array. We have to check whether each element has unique number of occurrences. If no such element is present then return false, otherwise true. So if the array is like [1, 1, 2, 2, 2, 3, 4, 4, 4, 4], then it will return true as the element 1 is present two times, 2 is present three times, 3 is present once and 4 is present four times.
To solve this, we will follow these steps −
- We will find the frequency of elements of the array
- for each key-value pair in the frequency map
- if value is present in another map mp, then return false
- put mp[value] := 1
- return true
Example
Let us see the following implementation to get better understanding −
class Solution(object): def uniqueOccurrences(self, arr): d = {} for i in arr: if i not in d: d[i] =1 else: d[i]+=1 l = {} for x, y in d.items(): if y in l: return False l[y] = 1 return True ob1 = Solution() print(ob1.uniqueOccurrences([1,1,2,2,2,3,4,4,4,4]))
Input
[1,1,2,2,2,3,4,4,4,4]
Output
true
Advertisements
To Continue Learning Please Login
Login with Google