[Solved] Why this code is not giving right result for large arrays? [closed]


Here is the correct code

#include<stdio.h>
#include<stdlib.h>
int main() {
    int t,T,n,i,j;
    long long int count,k;
    scanf("%d",&T);
    int *c = calloc(1000000,sizeof(int));      
    for(t=0;t<T;t++){
        scanf("%d",&n);
        int temp;
        count =0;

        for(i=0;i<n;i++){
            scanf("%d",&temp);
            c[temp-1]++ ;
        }

        for(i=0;i<1000000;i++){
            if(c[i]>1){
                k = c[i];
                count+= k*(k-1);
            }
            c[i] = 0;  
        }
        printf("%lld\n",count);

    }
    return 0;
}

Changes :

  • Used calloc to initialize the array to zero (don’t know why, but your
    method of array initialisation gives segmentation fault)
  • As the limit for n is 100000 hence the output may be as high as n^2 i.e. 10000000000 which out of int range, hence used long long int for count variable.

8

solved Why this code is not giving right result for large arrays? [closed]