-
Notifications
You must be signed in to change notification settings - Fork 20
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #47 from Dvd1234/main
Code to compute the pairs having a given sum
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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), | ||
*/ |