Print Duplicate element from an array

1.By using HashMap<key,value> under collection framework concept we can find the duplicate ones

Example

import java.util.HashMap;
import java.util.Map;

class Employee
{
public static void main(String args[])
{
int arr[] = {1,2,2,2,3,4,4 };
int size =arr.length;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<size;i++)
{
if(map.containsKey(arr[i]))
map.put(arr[i],0);
else
map.put(arr[i],1);
}
for(Map.Entry<Integer,Integer> entry : map.entrySet())
{
if(entry.getValue() == 0)
System.out.print(entry.getKey()+ " ");
}
}
}

Time Complexity: O(N)
Auxiliary Space: O(N)

2.If you dont need you use collection mean then we can achieve the result by using merge sort and bubble sort algorthim

merge sort — → for sorting the unsorted array

Bubble sort — — -> for Printing duplicate element from the sorted array

import java.util.Arrays;

class Employee
{
public static void main(String args[])
{
int[] values = {4,3,3,2,2,1,4};
int size = values.length;
sort(values,0,size-1);

System.out.println("Array is sorted"+Arrays.toString(values));

int[] temp = new int[size];
int j = 0;
for(int i=0;i<size-1;i++)
{
if(values[i] == values[i+1])
{
temp[j] = values[i];
j++;
}
}


for(int i=0;i<j;i++)
{
System.out.println("Sorted Result--"+temp[i]);
}


}
public static void sort(int values[],int low,int high)
{
if(low < high)
{
int middlelement = low + (high-low)/2;
sort(values,low,middlelement);
sort(values,middlelement+1,high);
merge(values,low,middlelement,high);
}
}
public static void merge(int[] values,int low,int middle,int high)
{
int n1 = middle - low +1;
int n2 = high - middle;

int[] L1 = new int[n1];
int[] L2 = new int[n2];

for(int i=0;i<n1;i++)
L1[i] = values[low+i];
for(int i=0;i<n2;i++)
L2[i] = values[middle+1+i];

int i=0,j=0,k=low;
while (i<n1 && j<n2)
{
if(L1[i] <= L2[j])
{
values[k] = L1[i];
i++;
k++;
}
else
{
values[k] = L2[j];
j++;
k++;
}
}
while (i<n1)
{
values[k] = L1[i];
i++;
k++;
}
while (j<n2)
{
values[k] = L2[j];
j++;
k++;
}
}
}