Skip to content

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=; 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; } }
Code language: Java (java)

See also  4 By 4 Skyscrapers in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x