Related Tags

python
community creator

# How to solve a problem on unique occurrences

Rithika Velicheti

## Problem

Given a list of integers, return whether or not the occurrence of every value in the array is unique.

Note: Numbers can be negative.

## Example 1

nums = [5, 3, 1, 8, 3, 1, 1, 8, 8, 8]

Output:- True


## Explanation

Element Ocuurrences
1 3
3 2
5 1
8 4

Since all occurrences are unique, it returns true.

## Example 2

Let’s try another example:

nums= [3, 1, 1, 2, 2, 2, 3]

## Algorithm

To solve this problem we need to:

1. find the number of times each element occurred
2. check the occurrence value – it should be uniquedifferent values for each element.

## Explanation

First, find out the occurrence number of each element in the given list(nums). Then, save the occurrence value/number in list_occur.

nums= [3, 1, 1, 2, 2, 2, 3]
list_element,list_occur=[],[]
for i in nums:
occur=nums.count(i) #no of occurrence
if(i not in list_element): #ignoring appending of reapted occurrence
list_element.append(i)  #appending elements which done counting occurrence
list_occur.append(occur) #occurrence values
print(list_occur)



Now, since we have the occurrence value of each element in the list, we have to check if the occurrence number of every value in the list is unique.

To do this, we just compare the values within list_occur.

nums= [3, 1, 1,1, 2, 2, 2, 3]
list_element,list_occur=[],[]
for i in nums:
occur=nums.count(i) #no of occurrence
if(i not in list_element): #ignoring appending of reapter occurrence
list_element.append(i)  #appending elements which done counting occurrence
list_occur.append(occur) #occurrence values
print(list_occur)
#checking occurrences are unique
for i in list_occur:
occur=list_occur.count(i)
if(occur>1):
print("False")
break
else:
print("True")

The whole program code is below, in the form of a function:

def solve(nums):
list_ele,list_occ=[],[]
for i in nums:
occur=nums.count(i)
if(i not in list_ele):
list_ele.append(i)
list_occ.append(occur)
for i in list_occ:
occur=list_occ.count(i)
if(occur>1):
return False
return True
print("nums=[3, 1, 1, 2, 2, 2, 3] ",solve([3, 1, 1, 2, 2, 2, 3]))
print("nums=[-3, -1, -1, -1, -2, -2] ",solve([-3, -1, -1, -1, -2, -2]))
print("nums=[5, 3, 1, 8, 3, 1, 1, 8, 8, 8] ",solve([5, 3, 1, 8, 3, 1, 1, 8, 8, 8]))

RELATED TAGS

python
community creator

CONTRIBUTOR

Rithika Velicheti
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 