From 738dec5ae638bdbae3d43990580a82aada7c0bfa Mon Sep 17 00:00:00 2001 From: Vidhish-Trivedi Date: Mon, 12 Sep 2022 22:45:31 +0530 Subject: [PATCH] Added solution --- 22. Pairs/solution.cpp | 44 +++++++++++++++++++++++++++++++++++ 22. Pairs/solution.py | 53 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 22. Pairs/solution.cpp create mode 100644 22. Pairs/solution.py diff --git a/22. Pairs/solution.cpp b/22. Pairs/solution.cpp new file mode 100644 index 0000000..517356c --- /dev/null +++ b/22. Pairs/solution.cpp @@ -0,0 +1,44 @@ +/* + Topic : Algorithms + Subtopic : Pairs + Language : C++ + 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. + Url : https://www.hackerrank.com/challenges/pairs/problem +*/ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +/* + * Complete the 'pairs' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER k + * 2. INTEGER_ARRAY arr + */ + +int pairs(int k, vector arr) { + map m; + for(int x : arr) + { + m[x]++; + } + int c = 0; + int i; + for(i = 0; i < arr.size(); i++) + { + m[arr[i]]--; + if(m[k + arr[i]] > 0) + { + c++; + } + m[arr[i]]++; + } + return(c); +} diff --git a/22. Pairs/solution.py b/22. Pairs/solution.py new file mode 100644 index 0000000..e134103 --- /dev/null +++ b/22. Pairs/solution.py @@ -0,0 +1,53 @@ +''' + Topic : Algorithms + Subtopic : Pairs + Language : Python 3 + 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. + Url : https://www.hackerrank.com/challenges/pairs/problem +''' +#!/bin/python3 + +import os + +# +# Complete the 'pairs' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER k +# 2. INTEGER_ARRAY arr +# + +def pairs(k, arr): + # Write your code here + m = {} + for _ in arr: + if(_ not in m.keys()): + m[_] = 1 + else: + m[_] += 1 + c = 0 + for i in range(len(arr)): + if((k + arr[i]) in m.keys()): + if(m[k + arr[i]] > 0): + c += 1 + m[arr[i]] += 1 + return(c) + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + first_multiple_input = input().rstrip().split() + + n = int(first_multiple_input[0]) + + k = int(first_multiple_input[1]) + + arr = list(map(int, input().rstrip().split())) + + result = pairs(k, arr) + + fptr.write(str(result) + '\n') + + fptr.close()