1.Contains duplicate
BeginnerWrite contains_duplicate(nums) that returns True if any value appears at least twice, in O(n) time. Test it on [1, 2, 3, 1] and [1, 2, 3, 4].
Show hint
Keep a set of values you have already seen.
Show solution
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
print(contains_duplicate([1, 2, 3, 1]))
print(contains_duplicate([1, 2, 3, 4]))True
FalseChecking membership in a set is O(1) on average, so the whole scan is O(n), compared with O(n²) for comparing every pair.