How do you detect whether an array contains a duplicate value, and what is the space trade-off?
Keep a set of the values you have already seen and check each new value against it before adding it. As soon as a value is found that is already in the set, you have a duplicate and can stop.
def contains_duplicate(values):
seen = set()
for value in values:
if value in seen:
return True
seen.add(value)
return False
print(contains_duplicate([1, 2, 3, 1]))
print(contains_duplicate([1, 2, 3]))The outputs are True and False. The first array contains 1 twice, and the second contains three distinct values.
The mechanism is the same as everywhere else in this family: a set turns the question of whether a value has been seen into a constant-time hash lookup. Comparing every pair of elements directly would be quadratic, while the set version is linear in the length of the array.
The trade-off to name is space. The set stores one entry per distinct value, so the memory grows with the input. For a duplicate check you do not actually need to store all the values, only the ones you have not yet seen, which is the same thing, so there is no way around the space cost with this approach. The alternative is to sort the data and look for adjacent equal elements, which uses no extra structure beyond what the sort needs but costs O of n log n time. For a large array under a tight memory budget, the sorting approach is the better trade, and for a large array with a generous budget, the set is faster.