Data Structures and Algorithms in Java – Arrays – Contains Duplicate


Given an array of numbers , find if there are any duplicates


numbers = [ 4, 7, 3, 9, 3]


true, since 3 is present twice


The number of elements in the array can be from 1 to a lakh.

The elements can be in the range of – 1 billion to + 1 billion

Try out the solution here:


The brute force solution is to iterate through the array and for each element check other elements in the array if they both match.

This requires two for loops and the time complexity is O(n2 ).

An optimal solution can be done in O(n) with an additional storage.


Use an additional data structure to keep track of elements traversed

Optimal Solution:


STEP1: Initialize an empty Hash Map

STEP2: Iterate through each element in the array

STEP3: For each element in the array check if the element already exists in the Hash Map , if it exists return true

STEP4: If element doesn’t exist , store the element as key and value as 1

STEP5: Return false if there are no duplicates as identified in STEP 3


class Solution {
    public boolean containsDuplicate(int[] nums) {
        var counterMap = new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
                return true;
        return false;

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s