The Contains Duplicate problem asks us to determine whether an array contains any value that appears more than once.

Problem

Given an integer array nums, return true if any value appears at least twice in the array. Otherwise, return false.

In other words, we need to determine whether the array contains any duplicate element.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

nums = [1, 2, 3, 1]

Output

true

Input

nums = [1, 2, 3, 4]

Output

false

Solution

This solution uses a HashSet to keep track of the elements that have already been encountered while traversing the array.

For each element, we first check whether it already exists in the set. If it does, the element is a duplicate, so we return true. Otherwise, we add the element to the set and continue scanning the array.

If the entire array is traversed without finding a duplicate, we return false.
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();

        for (int num : nums) {
            if (set.contains(num)) {
                return true;
            }
            set.add(num);
        }
        return false;
    }
}

Complexity

Each element is inserted into and searched in the HashSet in average O(1) time. Therefore, the overall time complexity is O(n), where n is the length of the array.

The HashSet can store up to n elements, so the extra space complexity is O(n).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion