Check if a Java array Contains Duplicates

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:

Leave a Reply

Your email address will not be published.