Leetcode [217] - Contains Duplicates (Java Solution)

Rugved avatar

Leetcode [217] - Contains Duplicates (Java Solution)
Category: Easy
What is used: HashSet


Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true
Explanation: 1 is repeated twice.

Example 2:

Input: [1,2,3,4]
Output: false
Explanation: No number in the array is repeated.

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true


  1. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100


I am using HashSet to solve this problem. There are various different methods to solve this problem but this is one the most straight forward and simple way. Learn more about HashSets here at: https://www.geeksforgeeks.org/hashset-in-java/

I traverse through the array and add elements one by one to the HashSet and as soon as the duplicate is encountered, return true. Else when entire array is traversed, return false.

class Solution {
	public boolean containsDuplicate(int[] nums) {
    		int i = 0;
    		HashSet<Integer> hs = new HashSet();
    		while (i < nums.length){
   			} else {
   				return true;
    		return false;

Time complexity:

The time complexity of this code is O(n)

Submission Details:

Runtime: 8 ms
Memory Usage: 44.1 MB