Contains Duplicate
Ever had that feeling of "Haven't I seen you before?" In Contains Duplicate, your mission is to tell us if any value in an array shows up at least twice. If there's even a single pair of twins hidden in the sequence, return true. If every single number is unique and flying solo, return false.
The "secret sauce" here is a Hash Set. Instead of using slow nested loops, you use a set as a smart "seen" list. As you walk through the array, you ask the set: "Is this number already checked in?" If the answer is yes, you found a duplicate! This approach is lightning fast (O(n) time) because set lookups are practically instant. It’s the most elegant and professional way to solve lookup problems in any application. Whether you're scanning log files or IDs, this pattern is a must-master skill!
Keep the algorithm focused on one clear invariant and update path so correctness is easy to verify from left to right. This reduces accidental branching errors and helps ensure the final output stays consistent with the problem contract across random and adversarial test shapes.
Examples
The value 1 appears more than once.
All values are distinct.
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.
