Skip to content

Count Pairs of Numbers with a Given Difference K

Ashish Sahu

Ashish Sahu

Asked Aug 7, 2015, 11:41 AM EDT1 answer
Share
LinkedInX
Hi Experts,
 
Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Return count of such pairs.
Example k=4 and a[]={7,623,19,10,11,9,3,15}
Output should be : 6
Pairs can be:
7,11(11-7=4)
7,3(7-3=4)
6,10(10-6=4)
19,23(23-19=4)
15,19(19-15=4)
15,11(15-11=4)
 
Please Help me.
 
Thanks & Regards
Ashish Kumar Sahu 

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Ashish Sahu
    0
    C#
    class ArraryDistinctPairs
        {
            static int countPairsWithDiffK(int[] arr, int n, int k)
            {
                int count = 0;
                for (int i = 0; i < n; i++)
                {
                    for (int j = i + 1; j < n; j++)
                        if (arr[i] - arr[j] == k || arr[j] - arr[i] == k)
                            count++;
                }
                return count;
            }
            static void Main()
            {
                int[] arr = { 7, 6, 23, 19, 10, 11, 9, 3, 15 };
                int n = arr.Length;
                int k = 4;
                Console.WriteLine("Count of pairs with given diff is " + countPairsWithDiffK(arr, n, k));
                Console.ReadLine();
            }
        }
    0