Contains duplicate
Does any value appear twice in the array? A hash set answers in a single pass, no sorting required.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
HashSet<T>.Add both inserts a value and tells you whether it was already there, in one call. Walk the array once: the first time Add would return false, that value has been seen before, so the array contains a duplicate.
Code
public static bool ContainsDuplicate(int[] a) {
var seen = new HashSet<int>();
foreach (int x in a) {
if (!seen.Add(x)) return true;
}
return false;
}static boolean containsDuplicate(int[] a) {
Set<Integer> seen = new HashSet<>();
for (int x : a) {
if (!seen.add(x)) return true;
}
return false;
}bool containsDuplicate(const vector<int>& a) {
unordered_set<int> seen;
for (int x : a) {
if (!seen.insert(x).second) return true;
}
return false;
}def contains_duplicate(a: list[int]) -> bool:
seen = set()
for x in a:
if x in seen: return True
seen.add(x)
return FalseTips
- Add returns a bool - true for a brand new value, false if it was already in the set - so a separate Contains check is never needed.
- Sorting first also finds duplicates, in O(n log n). The hash set does it in one O(n) pass.
In the .NET library
A HashSet<T> is really a Dictionary<T,bool> under the hood: the same O(1) average lookup, but it only needs to remember whether a key exists, not a paired value.