The 30 second answer
I add every number to a HashSet. Set add returns false when the element is already there, so the first false means there is a duplicate and I return true right away. That is linear time and linear space. If memory matters more, I can sort and compare neighbours in n log n time.
Problem Return true if any value appears at least twice in the array, otherwise false. Original: LeetCode 217: Contains Duplicate.
Understanding the prompt You only need a yes or no, not which value repeats or how many times. That allows an early exit.
Pattern recognition "Have I seen this before?" is a membership check, which a hash set answers.
Brute force Compare every pair: O(n²) time.
Optimal Use a HashSet. Set.add returns false when the set already contains the element, so you can test and insert in one call.
Alternatives Sort, then compare adjacent elements. That is O(n log n) time with little extra memory, but it changes the input array unless you copy it first.
Java solution
import java.util.HashSet;
public class ContainsDuplicate {
static boolean containsDuplicate(int[] nums) {
var seen = new HashSet<Integer>();
for (int x : nums) {
if (!seen.add(x)) return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(containsDuplicate(new int[] {1, 2, 3, 1})); // true
System.out.println(containsDuplicate(new int[] {1, 2, 3, 4})); // false
System.out.println(containsDuplicate(new int[] {})); // false
}
}Complexity O(n) expected time and O(n) space for the set.
Edge cases
- An empty array or a single element returns false.
- Negative numbers and zero work like any other value.
Follow-ups
- Duplicates within distance k (LeetCode 219): keep a set limited to the last k elements.
- Not allowed extra memory: sort in place.
Tests [1,2,3,1] returns true. [1,2,3,4] returns false. [] returns false.
How to say it in the interview "I put each number into a hash set. add returns false when the value is already there, so I stop at the first duplicate. That's O(n) time and O(n) space. If memory is tight, I'd sort and compare neighbours in O(n log n)."
Sources (2)
- LeetCode 217: Contains Duplicateleetcode.com
- Java SE 17 API: Set.adddocs.oracle.com