BudiBadu Logo

Contains Duplicate

Hash Table Easy 8 views
Like0

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

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

All values are distinct.

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

Recommendation Algorithm Flow for Contains Duplicate - Budibadu
Recommendation Algorithm Flow for Contains Duplicate - Budibadu

Best Answers

java
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;
    }
}