Video in progress
How do you quickly find out whether an array contains a duplicate element?
I add elements to a HashSet one by one: if add returns false, that element was seen before. Time is O(n) on average, memory is O(n). If memory is tight, you can sort and compare neighbors, which is O(n log n).
📖 Answer
static boolean hasDuplicate(int[] a) {
Set<Integer> seen = new HashSet<>();
for (int v : a) {
if (!seen.add(v)) return true;
}
return false;
}
Set.add returns false if the element is already there, so a separate contains call isn't needed.
Comparing the three options:
- nested loops: O(n²), memory O(1). Not bad on a small array, useless on a large one;
- sort + neighbors: O(n log n), but it modifies the input array;
HashSet: O(n), but it allocates an object and a node for everyInteger.
If the values are in a small range (say 0 to 1000), boolean[] seen = new boolean[1001] is the fastest. That's why asking about the range of values in an interview is useful.
Sign up to mark studied questions and save your progress.