Trying to reverse engineer the interview rejection reason is typically a difficult and often meaningless exercise, so let's reform the question to something more fun and continue to improve on your answer, as you would have if you had been given more time.
Write a function that is given an array of integers. It should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
def containsDuplicate(arr):
hashi={}
for i in arr:
try:
hashi[i]+=1
return 1
except KeyError:
hashi[i]=1
return 0
Well, python has a style guide that suggests some spacing, so let's do that. (No one would ever reject someone for this, btw)
Python also uses True
and False
more then the C style 0 and 1s for booleans.
def containsDuplicate(arr):
hashi = {}
for i in arr:
try:
return True
except KeyError:
hashi[i] = 1
return False
Now, Python officially subscribes to EAFP where you use exceptions rather then checking, but some people disagree. If you used checking, we have:
def containsDuplicate(arr):
hashi = {}
for i in arr:
if i in hashi:
return True
else:
hashi[i] = True
return False
However, time to get clever. Using sets, we can do:
def containsDuplicate(a):
return len(set(a)) != len(a)