Hacker Rank Solutions For Sherlock-and-Pairs

Sherlock is given an array of N integers A0, A1 ... AN-1 by Watson. Now Watson asks Sherlock that how many different pairs of indices i and j exist such that i is not equal to j but Ai is equal to Aj.

That is, Sherlock has to count total number of pairs of indices (i, j) where Ai = Aj AND i ≠ j.

Input Format 

First line contains T, the number of testcases. T test case follows.

Each testcase consists of two lines, first line contains an integer N, size of array.

Next line contains N space separated integers.

Output Format 

For each testcase, print the required answer in different line.

Constraints 

1 ≤ T ≤ 10

1 ≤ N ≤ 105

1 ≤ A[i] ≤ 106

Sample input

2

3

1 2 3

3

1 1 2

Sample output

0

2

Explanation 

In the first testcase, no two pair of indices exist which satisfy the given property.

In second testcase as A[0] = A[1] = 1, the pairs of indices (0,1) and (1,0) satisfy the given property.


Solution:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int t,T,n,i,j,temp;
    long long int count,k;
    scanf("%d",&T);
    int c[1000000] = {0};
    for(t=0;t<T;t++){
        scanf("%d",&n);
        int a[n];
        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;
}





No comments:

Post a Comment