Largest Unique Number in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers, we have to return the number whose occurrence is 1, if no such element is present, then return -1. So if the list is like [5,2,3,6,5,2,9,6,3], then the output will be 9.

To solve this, we will follow these steps −

  • We will check each element, and put the elements inside the map, so if the element is not in map, then put a new entry, otherwise increase the value

  • then go through the map, when the value is 1, return the key.

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def largestUniqueNumber(self, A):
      d = {}
      ans = -1
      for i in A:
         if i not in d:
            d[i]=1
         else:
            d[i] +=1
      for a,b in d.items():
         if b == 1:
            ans = max(a,ans)
      return ans
ob1 = Solution()
print(ob1.largestUniqueNumber([5,2,3,6,5,2,9,6,3]))

Input

[5,2,3,6,5,2,9,6,3]

Output

9
raja
Published on 27-Feb-2020 11:42:12
Advertisements