Use dictionary lookup to avoid repeated searches
A dictionary records information you will need later. For duplicate detection, a set is enough: check membership before inserting each value. Average lookup is constant time, so the full scan takes expected O(n) time and O(n) extra space. Hash collisions can worsen performance; do not treat this as a worst-case guarantee.
def has_duplicate(values):
seen = set()
for value in values:
if value in seen:
return True
seen.add(value)
return False
assert has_duplicate([2, 7, 2])
assert not has_duplicate([2, 7])These examples use Python 3 and include assertions you can run locally.
Try an original practice problem