Contains Duplicate
Given an integer array nums, return true if any value appears at least twice. Return false if every element is distinct.
This is one of the cleanest hash table problems because the idea is simple: scan the array once, keep a set of values you have already seen, and stop immediately when a number shows up again. If you finish the scan without hitting a repeat, then all values were unique.
Budibadu uses this problem to build the habit of using a set for fast lookups instead of wasting time on nested loops. It is a small pattern, but it shows up everywhere.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Explanation: The value 1 appears more than once.
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation: Every number appears exactly once.
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Explanation: Several values repeat, so the answer is true.
Algorithm Flow

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 problem.
