Skip to content

Commit

Permalink
Merge pull request #47 from Dvd1234/main
Browse files Browse the repository at this point in the history
Code to compute the pairs having a given sum
  • Loading branch information
narayancseian authored Oct 6, 2022
2 parents 2f8ea6d + fbcaccf commit 5189dc7
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Array/CountPairsWithGivenSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package java;

import java.util.*;
/*
Given an array of N integers, and a number sum, the task is to find the number of pairs of integers
in the array whose sum is equal to sum.
*/

class PairWithGivenSum {

static int getPairsCount(int arr[], int n, int k)
{
HashMap<Integer, Integer> m = new HashMap<>();
int count = 0;
for (int i = 0; i < n; i++) {
if (m.containsKey(k - arr[i])) {
count += m.get(k - arr[i]);
}
if (m.containsKey(arr[i])) {
m.put(arr[i], m.get(arr[i]) + 1);
}
else {
m.put(arr[i], 1);
}
}
return count;
}

public static void main(String[] args)
{
int arr[] = { 1, 5, 7, -1, 5 };
int sum = 6;
System.out.print("Count of pairs is " + getPairsCount(arr, arr.length, sum));
}
}
/*
Time Complexity: O(n),
Auxiliary Space: O(n),
*/

0 comments on commit 5189dc7

Please sign in to comment.