Contains Duplicate
You are given an array of numbers and need to decide whether any value appears more than once.
The exact position does not matter. As soon as the same number shows up again anywhere in the array, the answer becomes true. If every value is different, the answer is false.
For example, nums = [1,2,3,1] returns true because 1 appears twice. nums = [1,2,3,4] returns false because all values are distinct.
So this problem is just asking whether the array contains at least one repeated value.
Example Input & Output
The value 1 appears more than once.
All values are distinct.
Several values repeat, so the answer is true.
Algorithm Flow

Solution Approach
A hash set is enough here.
Walk through the array and keep every value you have seen so far in the set. For each new number, check whether it is already in the set. If it is, return true right away because you found a duplicate. If not, add it and continue.
If the loop finishes without finding a repeat, return false. This runs in O(n) expected time with O(n) extra space.
Best Answers
import java.util.*;
class Solution {
public boolean contains_duplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) return true;
seen.add(num);
}
return false;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
