Check if a Java array Contains Duplicates

0 min read 139 words

The challenge

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

Example 2:

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

Example 3:

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

The solution

class Solution {
    // return a boolean from the primitive int array input
    public boolean containsDuplicate(int[] nums) {
        // create a HashMap to hold our values
        HashMap<Integer, Integer> hm = new HashMap<>();
        
        // loop through the input array
        for (int i=0; i<nums.length; i++) {
            // return true if we have seen a duplicate
            // otherwise add the int to the HashMap
            if (hm.get(nums[i])!=null) return true;
            else hm.put(nums[i], 1);
        }
        
        // return false if all else fails
        return false;
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags