Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is duplicate elements in array?
3.
How to find Duplicates Elements in Array?
3.1.
Code
3.2.
Java
3.3.
Output
4.
Remove Duplicates Element in Array Using Nested Loops
4.1.
Example
4.2.
Algorithm
4.3.
Program
4.4.
Java
4.5.
Output
4.6.
Time Complexity
5.
Remove Duplicates Element in Array Using Hashmap Method
5.1.
Algorithm
5.2.
Program
5.3.
Java
5.4.
Output
5.5.
Time and Space Complexity
6.
Frequently Asked Questions
6.1.
Can array list have duplicates?
6.2.
What are duplicate elements in Java?
6.3.
How do you find duplicates in an array of Java?
6.4.
How to remove duplicates in array using Java?
7.
Conclusion
Last Updated: Apr 4, 2024
Easy

Print Duplicate Elements in Array

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Dealing with arrays is a common task in programming, and one of the challenges developers often encounter is finding duplicate elements within an array. Whether you're working on data analysis, algorithmic problems, or software development, identifying and handling duplicate elements efficiently is crucial for maintaining the integrity and accuracy of your programs.

Print Duplicate Elements in Array

In this post, we will explore identifying and printing duplicate elements in an array using two methods. The first one is using two nested for loops and the second one is using the hashmap method. Before moving on to the program for displaying duplicate elements in an array, we will cover a few basics of the array data structure. 

I hope you will enjoy learning about this topic. So, let’s get started with our article on “Print Duplicate Elements in Array”.

Click here to know about Array in Javascript here.

What is duplicate elements in array?

Duplicate elements in an array are those elements that appear more than once within the array. In other words, if there are two or more occurrences of the same value in an array, those values are considered duplicates. Identifying duplicate elements in an array is a common programming task, and it often involves searching through the array to find and handle these repeated values appropriately.

Example of array declaration in Java:

int a[]=new int[10];
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to find Duplicates Elements in Array?

To find duplicate elements in a Java array, you can use various approaches. One common method is to use nested loops to compare each element with others. Here's a step-by-step explanation:

  • Initialize a loop that iterates over each element in the array.
     
  • For each element in the outer loop, start an inner loop that iterates from the next element to the end of the array.
     
  • Inside the inner loop, compare the current element from the outer loop with the elements in the inner loop.
     
  • If a match is found (i.e., if two elements have the same value), it means you've found a duplicate element.
     
  • You can then record or print the duplicate element, store it in a separate data structure, or take any other desired action.

 

Code

  • Java

Java

public class FindDuplicates {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 2, 5, 6, 3};

for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
System.out.println("Duplicate found: " + array[i]);
}
}
}
}
}

Output

Duplicate found: 2
Duplicate found: 3


Check out this problem - Find Duplicate In Array

Remove Duplicates Element in Array Using Nested Loops

We need to print the duplicate elements in the array in this program. We can use two loops to do this. The first loop selects an element, while the second loop iterates across the array by comparing the selected element to other elements. If a duplicate element is detected, print it.

Example

Elements: 9 7 8 6 8 5 5 6 3 2

 

The first duplication in the above array occurs at index 4, duplicating the element (8) at index 2. In the above array, the duplicate entries are 5, 6, 8.

Algorithm

  1. Create and initialise an array.
  2. Use two loops to find duplicate components - the outer loop iterates across the array from 0 to the array's length. The outer loop will choose the element. The selected element will be compared to the rest of the array's elements using the inner loop.
  3. If there is a match, it signifies the duplicate element is there, so display it.

Program

  • Java

Java

/*Program to display duplicate elements of an array*/
import java.util.*;
class ArrayDuplicate{ 
   public static void main(String[] args) {     
       
       //Input the number of elements in the array. 
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter the size of array");
       int n=sc.nextInt();
       int arr[]=new int[n];
       //Input the elements of the array.
       System.out.println("Enter the elements of array");
       for(int i=0;i<n;i++)
       {
           arr[i]=sc.nextInt();
       }  //end of for loop 
       System.out.println("Duplicate elements are: "); 
       //Search for duplicate element 
       for(int i = 0; i < arr.length; i++) { 
           for(int j = i + 1; j < arr.length; j++) { 
               if(arr[i] == arr[j]) 
                   System.out.println(arr[j]); 
           } 
       } 
   } 
}

Output

Enter the size of array
9
Enter the elements of array
9 7 8 6 8 5 5 6 3 2 
Duplicate elements are: 
8
6
5


We took the user’s inputs in the Java program above. We've now iterated all possible pairs in the array using two for loops. If two elements are equal, we display the element in the output.

Time Complexity

This method has a time complexity of O(n2). This is because we are iterating ‘n’ elements using two for loops.

Must Read Array of Objects in Java

Remove Duplicates Element in Array Using Hashmap Method

In this method, we have used the Hashmap in Java to find duplicate elements. The elements of the input array are stored as keys in the HashMap, and their occurrences are stored as values in the HashMap. Before going into the program, we will go through the algorithm to have a clear understanding of the underlying working steps of the program.

Algorithm

  1. Make a HashMap with a key and value pair of integers.
  2. Iterate through your array, checking whether each member is present in the HashMap using the ContainsKey() function.
  3. If it isn't already in the HashMap, use the put() function to add it.
  4. If it exists in the HashMap, mark it as a duplicate element and proceed.

Program

  • Java

Java

//java program to find duplicate elements in an array using hashmap
import java.util.*;
class ArrayDuplicate
{
   public static void main(String args[])
   {
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter the size of array");
       int n=sc.nextInt();
       int a[]=new int[n];
       System.out.println("Enter the elements of array");
       for(int i=0;i<n;i++)
       {
           a[i]=sc.nextInt();
       }
       HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
       for(int i=0;i<n;i++)
       {
           if(hm.containsKey(a[i]))
           {
               hm.put(a[i],hm.get(a[i])+1);
           }
           else
           {
               hm.put(a[i],1);
           }
       }
       System.out.println("Duplicate elements are");
       for(Map.Entry<Integer, Integer> entry : hm.entrySet()) {
if(entry.getValue()>1) {
System.out.println(entry.getKey());
}
}
   }
}

Output

Enter the size of array
9
Enter the elements of array
9 7 8 6 8 5 5 6 3 2 
Duplicate elements are: 
8
6
5

 

Try it by yourself on java online compiler.

Time and Space Complexity

The time complexity is O(n). In the hashmap method, we are visiting each element of the array only once. So, the time complexity is of order ‘n.’

The space complexity is also O(n) to store the elements.

Also check out Addition of Two Numbers in Java.

Frequently Asked Questions

Can array list have duplicates?

Yes, an array can have duplicate values. 

What are duplicate elements in Java?

In Java, duplicate elements refer to having the same value or content appearing more than once in a data structure like an array, list, or set. It's when there are multiple identical elements in a collection.

How do you find duplicates in an array of Java?

To find duplicates in a Java array, you can use a HashSet or nested loops. With a HashSet, you add elements to the set as you iterate through the array, and if an element is already in the set, it's a duplicate. Using nested loops, compare each element with others and flag duplicates when found.

How to remove duplicates in array using Java?

To remove duplicates from a Java array, you can use a HashSet or create a new array. With a HashSet, add elements to the set while iterating through the original array, then convert the set back to an array. Alternatively, use nested loops to filter out duplicates and create a new array with unique elements.

Conclusion

In this article, we have discussed how to find duplicate elements in array. Understanding the problem of finding duplicate elements in arrays is a valuable skill for any programmer. Throughout this guide, we've explored various techniques and strategies, ranging from simple brute-force methods to more optimized algorithms.

Recommended Read: 

Array in Python

We hope you've better understood basic java programming and the program to find duplicate elements in an array. If you're interested in finding out more, see our articles on print characters in a string and selenium interview questions.

Visit our practice platform Coding Ninjas Studio to get started. Here you can practice top problems, attempt mock tests, read interview experiences, and more.!

Happy Reading!

Previous article
How to Sort List in Java
Next article
Program to find all Punctuations in a String
Live masterclass