Find All Duplicates in an Array in java

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, print an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Input:

The first line contains a single integer n(size of array n) Second line contains n spaced integers

Output:

Print all the elements that appear twice in sorted manner

Constraints

```1 <= n <= 10^5
```
Sample Input 1

8 4 3 2 7 8 2 3 1

```2 3
```
```3
1 1 2
```
`1`

Solution of Find All Duplicates in an Array in java:–

```import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];

for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}

Arrays.sort(arr);

for(int i=0;i<n-1;i++)
{

if(arr[i]==arr[i+1])
{
System.out.print(arr[i]+" ");
}

}
}
}```