Find All Duplicates in an Array in java

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.


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


Print all the elements that appear twice in sorted manner


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

8 4 3 2 7 8 2 3 1

Sample Output 1
2 3
Sample Input 2
1 1 2
Sample Output 2

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

import java.util.*;
import java.lang.*;

public class Main
	public static void main (String[] args) throws java.lang.Exception
		//your code here
      Scanner sc=new Scanner(;
      int n=sc.nextInt();
      int[] arr=new int[n];
      for(int i=0;i<n;i++)
      for(int i=0;i<n-1;i++)
             System.out.print(arr[i]+" ");

Add a Comment

Your email address will not be published. Required fields are marked *