TLE error in my code to count how many duplicate elements are there in an array! What's Wrong in my code?

Viewed 27

I want to count the number of duplicate elements in an array. My code works fine in my Compiler but when I try to submit my code it shows TLE(Time Limit Exceeded) Error. My code is here:

public static void main(String[] args) throws IOException {
    Scanner s= new Scanner(System.in);
    long count=0;
    long n=s.nextLong();
    for(int i=0; i<n; i++) {
        int g=s.nextInt();
        int []arr=new int [g];
        for(int j=0; j<g; j++) {
            arr[j]=s.nextInt();
        }
        for(int j=0; j<g; j++) {
            for(int k=j+1; k<g; k++) {
                if(arr[j]==arr[k]) {
                    count++;
                }
            }
        }
        System.out.println(count);
        count=0;
    }
}

}
1 Answers

run this code it perfectly works you asked for some extra value which is not needed

public static void main(String[] args){
    Scanner s= new Scanner(System.in);
    long count=0;
    //long n=s.nextLong(); // there is NO NEED for this line !
    //for(int i=0; i<n; i++) { // there is NO NEED for this line !
        int g=s.nextInt();
        int []arr=new int [g];
        for(int j=0; j<g; j++) {
            arr[j]=s.nextInt();
        }
        for(int j=0; j<g; j++) {
            for(int k=j+1; k<g; k++) {
                if(arr[j]==arr[k]) {
                    count++;
                }
            }
        }
        System.out.println(count);
        count=0;
    //} // there is NO NEED for this line !
}
Related