Sunday, June 26, 2022

Count duplicates

Count duplicates

Problem Statement

Given an array of N elements, your task is to find the count of repeated elements. Print the repeated elements in ascending order along with their frequency.
Have a look at the example for more understanding.
import java.util.Arrays;
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
 
public class Main {
    // Function to display the repeated elements and their frequencies 
    static void displayOutput(int[] a){
        int i,j,frequency;
        for(i=0; i<a.length; i++){
            frequency = 1;
            for(j=i+1; j<a.length; j++){
                if(a[j] == a[i]){
                    frequency++;
                }
                else{
                    break;
                }
            }
            i=j-1;
            if(frequency > 1){
                System.out.println(a[i] 
                                   + " " + frequency);
            }
        }
    }
    public static void main (String[] args) {
        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);
        displayOutput(a);
    }
}

No comments:

Post a Comment

ads vert

Basic HTML Tables - Layout, HTML Tables, Attributes, Aside, Footer, Tr tag, Td tag, Th tag, Tbody

  Basic HTML Tables - Layout, HTML Tables, Attributes, Aside, Footer, Tr tag, Td tag, Th tag, Tbody < table >      < thead >    ...