# Program to find duplicate elements and delete last occurrence of them in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers A, we have to find all duplicate numbers and remove their last occurrences.

So, if the input is like [10, 30, 40, 10, 30, 50], then the output will be [10, 30, 40, 50]

To solve this, we will follow these steps −

• seen:= a new map
• d:= a new map
• for i in range 0 to size of nums, do
• if nums[i] is not in d, then
• d[nums[i]]:= 1
• otherwise,
• d[nums[i]] := d[nums[i]] + 1
• i:= 0
• while i < size of nums, do
• n:= d[nums[i]]
• if nums[i] is not in seen, then
• seen[nums[i]]:= 1
• otherwise,
• seen[nums[i]] := seen[nums[i]] + 1
• if n is same as seen[nums[i]] and n > 1, then
• delete ith element from nums
• i := i - 1
• i := i + 1
• return nums

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums):
seen={}
d={}
for i in range(len(nums)):
if not nums[i] in d:
d[nums[i]]=1
else:
d[nums[i]]+=1
i=0
while i < len(nums):
n=d[nums[i]]
if not nums[i] in seen:
seen[nums[i]]=1
else:
seen[nums[i]]+=1
if n == seen[nums[i]] and n > 1:
nums.pop(i)
i-=1
i+=1
return nums
ob = Solution()
print(ob.solve([10, 30, 40, 10, 30, 50]))

## Input

[10, 30, 40, 10, 30, 50]

## Output

[10, 30, 40, 50]
Updated on 07-Oct-2020 13:31:41