Finding the minimum unique number in an array

Viewed 2086

The minimum unique number in an array is defined as min{v|v occurs only once in the array} For example, the minimum unique number of {1, 4, 1, 2, 3} is 2. Is there any way better than sorting?

3 Answers

Python version using dictionary.
Time complexity O(n) and space complexity O(n):

from collections import defaultdict
d=defaultdict(int)
for _ in range(int(input())):
    ele=int(input())
    d[ele]+=1
m=9999999
for i in d:
    if d[i]==1 and i<m:
        m=i
print(m if m!= 9999999 else -1)

Please tell me if there is a better approach.

Related