Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

HackerRank Pairs problem solution

YASH PAL, 31 July 202410 September 2024

In this HackerRank Pairs interview preparation kit problem You are 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.

HackerRank Pairs Interview preparation kit solution

Problem solution in Python programming.

#!/usr/bin/py
# Head ends here
def pairs(a,k):
    # a is the list of numbers and k is the difference value
    a.sort()
    left = 0
    right = 1
    answer = 0
    while right < len(a):
        val = a[right]-a[left]
        if val == k:
            answer += 1
            left += 1
            right += 1
        elif val < k:
            right += 1
        else:
            left += 1
            if left == right:
                right += 1

    return answer
# Tail starts here
if __name__ == '__main__':
    a = input().strip()
    a = list(map(int, a.split(' ')))
    _a_size=a[0]
    _k=a[1]
    b = input().strip()
    b = list(map(int, b.split(' ')))
    print(pairs(b,_k))

Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        int counter = 0;
        Set<Integer> nums = new HashSet<Integer>();
        for (int i =0; i < n; i++) {
            int m = scanner.nextInt();
            if (nums.contains(m-k))
                counter++;
            if (nums.contains(m+k))
                counter++;
            nums.add(m);
        }
        System.out.println(counter);
    }
}

Problem solution in C++ programming.

#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;
}

Problem solution in C programming.

#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("%dn",count);
return 0;
}

Problem solution in JavaScript programming.

var buff='';
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) {
    buff+=input;
});
process.stdin.on("end", function () {    
    var input=buff;
    var k=parseInt(/d+s(d+)/.exec(input)[1]);
	var data=input.split('n')[1].split(' ');
	var length=data.length;
    var hash={};
	var counter=0;
	for(var i=0;i<length;i++){
         var d=parseInt(data[i]);
         hash[d]=1;
         if(hash[d+k]){
             counter++;
         }
         if(hash[d-k]){
             counter++;
         }      
	}
   	
    process.stdout.write(counter);
    
});
                 

coding problems solutions interview prepration kit

Post navigation

Previous post
Next post

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes