Print Repeated Elements in Sorted Order in java

Print Repeated Elements in Sorted Order in java

You are given an array A of size N. The array contains almost distinct elements with some duplicated. You have to print the elements in sorted order which appears more than once. If no such element exist print -1.

Input Format

The first line of input contains size of array N.

The second line contains N integers separated by spaces denoting elements of array.

Output Format

Print elements which occurs more than once in array in sorted order. If no such element exist print -1

Example 1

Input

9
3 4 5 7 8 1 2 1 3

Output

1 3

Explaination

1 and 3 both occur 2 times in this array .

Example 2

Input

5
1 2 3 4 5

Output

-1

Explaination

No element is repeated here

Constraints

1 <= N < 10^5

0 <= A[i] <= 10^5

Solution of Print Repeated Elements in Sorted Order in java:–

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

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc=new Scanner(System.in);
      int n=sc.nextInt();
      int []a=new int[n];
      for(int i=0;i<n;i++)
        {
          a[i]=sc.nextInt();
        }
      Arrays.sort(a);
      int index=-1;
      int element=Integer.MIN_VALUE;
      for(int i=0;i<n-1;i++)
        {
          if(a[i]==a[i+1])
          {
             index=i;
            if(a[i]!=element)
            {
              System.out.print(a[index]+" ");
            }
          }
          element=a[i];
        }
      if(index<0)
      {
        System.out.print(index);
      }
	}
}

Add a Comment

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