Skip to content

Commit 566f84c

Browse files
committed
count pairs given sum
1 parent a2d2760 commit 566f84c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

DSA Crack Sheet/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
- [Next Permutation](https://leetcode.com/problems/next-permutation/ "view question") - [Cpp Solution](./solutions/Next%20Permutation.cpp)
1919
- [Count Inversions](https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1# "view question") - [Cpp Solution](./solutions/Count%20Inversions.cpp)
2020
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ "view question") - [Cpp Solution](./solutions/Best%20Time%20to%20Buy%20and%20Sell%20Stock.cpp)
21+
- [Count pairs with given sum](https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1# "view question") - [Cpp Solution](./solutions/Count%20pairs%20with%20given%20sum.cpp)
2122
- []( "view question") - [Cpp Solution](./solutions/.cpp)
2223

2324
<!-- - []( "view question") - [Cpp Solution](./solutions/) -->
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Count pairs with given sum
3+
==========================
4+
5+
Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.
6+
7+
Example 1:
8+
Input:
9+
N = 4, K = 6
10+
arr[] = {1, 5, 7, 1}
11+
Output: 2
12+
Explanation:
13+
arr[0] + arr[1] = 1 + 5 = 6
14+
and arr[1] + arr[3] = 5 + 1 = 6.
15+
16+
Example 2:
17+
Input:
18+
N = 4, X = 2
19+
arr[] = {1, 1, 1, 1}
20+
Output: 6
21+
Explanation:
22+
Each 1 will produce sum 2 with any 1.
23+
Your Task:
24+
You don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K.
25+
26+
Expected Time Complexity: O(N)
27+
Expected Auxiliary Space: O(N)
28+
29+
Constraints:
30+
1 <= N <= 105
31+
1 <= K <= 108
32+
1 <= Arr[i] <= 106
33+
*/
34+
35+
int getPairsCount(int arr[], int n, int k)
36+
{
37+
unordered_map<int, int> freq;
38+
for (int i = 0; i < n; ++i)
39+
freq[arr[i]]++;
40+
int ans = 0;
41+
for (int i = 0; i < n; ++i)
42+
{
43+
ans += freq[k - arr[i]];
44+
if (k == 2 * arr[i])
45+
ans--;
46+
}
47+
return ans / 2;
48+
}

0 commit comments

Comments
 (0)