Pairs


Problem Statement :


Given an array of integers and a target value, determine the number of pairs of array elements that have a difference equal to the target value.


Function Description

Complete the pairs function below.

pairs has the following parameter(s):

int k: an integer, the target difference
int arr[n]: an array of integers
Returns

int: the number of pairs that satisfy the criterion
Input Format

The first line contains two space-separated integers n and k, the size of arr and the target value.
The second line contains n space-separated integers of the array arr .

Constraints

2   <=   n   <=   10^5
0   <=   k   <=   10^9
0   <=   arr[ i ]  <=  2^31 -1
each integer arr[ i ]  will be unique

Sample Input

STDIN          Function
-----                 --------
5 2              arr[] size n = 5, k =2
1 5 3 4 2    arr = [1, 5, 3, 4, 2]


Sample Output

3



Solution :



title-img


                            Solution in C :

In   C++  :





#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
/* Head ends here */

int pairs(vector <int> a,int k) {
    int ans = 0;
    set<long long> s;
    for(int i = 0; i < a.size(); i++) s.insert(a[i]);
    for(int i = 0; i < a.size(); i++){
        long long b = a[i] - k;
        if(s.count(b)) ans ++;
    }
    return ans;
}

/* Tail starts here */
int main() {
    int res;
    
    int _a_size,_k;
    cin >> _a_size>>_k;
    cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
    vector<int> _a;
    int _a_item;
    for(int _a_i=0; _a_i<_a_size; _a_i++) {
        cin >> _a_item;
        _a.push_back(_a_item);
    }
    
    res = pairs(_a,_k);
    cout << res;
    
    return 0;
}







In  Java  :







import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int pairs(int[] a,int k) {
        Arrays.sort(a);
        int N = a.length;
		int count = 0;
		for (int i = 0; i < N - 1; i++)
		{
			int j = i + 1;
			while((j < N) && (a[j++] - a[i]) < k);
			j--;
			while((j < N) && (a[j++] - a[i]) == k)
				count++;			
		}

        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;
        
        String n = in.nextLine();
        String[] n_split = n.split(" ");
        
        int _a_size = Integer.parseInt(n_split[0]);
        int _k = Integer.parseInt(n_split[1]);
        
        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");
        
        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }
        
        res = pairs(_a,_k);
        System.out.println(res);
    }
}







In   C :





#include<stdio.h>
int get_num()
{
int num=0;
char c=getchar_unlocked();
while(!(c>='0' && c<='9'))
c=getchar_unlocked();
while(c>='0' && c<='9')
{
num=(num<<3)+(num<<1)+c-'0';
c=getchar_unlocked();
}
return num;
}
void quicksort(int x[],int first,int last)
{
    int pivot,j,temp,i;

     if(first<last)
    {
         pivot=first;
         i=first;
         j=last;

         while(i<j){
             while(x[i]<=x[pivot]&&i<last)
                 i++;
             while(x[j]>x[pivot])
                 j--;
             if(i<j){
                 temp=x[i];
                  x[i]=x[j];
                  x[j]=temp;
             }
         }

         temp=x[pivot];
         x[pivot]=x[j];
         x[j]=temp;
         quicksort(x,first,j-1);
         quicksort(x,j+1,last);

    }
}
int main()
{
int n=get_num();
int k=get_num();
int a[100000]={0};
int i=0;
while(i<n)
a[i++]=get_num();
quicksort(a,0,n-1);
int temp=0,count=0,flag=0;
for(i=0;i<n-1;i++)
{
int j=i+1;
temp=0;
for(;j<n;j++)
{
if(a[j]-a[i]==k)
count++;
else if(a[j]-a[i]>k)
break;
}
}
printf("%d\n",count);
return 0;
}








In  Python3 :





def main():
	N, K = (int(x) for x in sys.stdin.readline().split())
	A = [int(x) for x in sys.stdin.readline().split()]
	setA = set(A)
	count = 0
	for x in A:
		if (x-K) in setA:
			count = count +1
	print (count)

if __name__ == '__main__':
	import sys
	main()
                        








View More Similar Problems

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →