Skip to content

Commit 5887e42

Browse files
authored
Create Pair Sum to 0
1 parent 1197eaa commit 5887e42

File tree

1 file changed

+74
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 16 - HashMaps

1 file changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
Given a random integer array A of size N. Find and print the count of pair of elements in the array which sum up to 0.
3+
Note: Array A can contain duplicate elements as well.
4+
5+
Input format:
6+
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
7+
The following line contains N space separated integers, that denote the value of the elements of the array.
8+
9+
Output format :
10+
The first and only line of output contains the count of pair of elements in the array which sum up to 0.
11+
12+
Constraints :
13+
0 <= N <= 10^4
14+
Time Limit: 1 sec
15+
16+
Sample Input 1:
17+
5
18+
2 1 -2 2 3
19+
Sample Output 1:
20+
2
21+
*/
22+
import java.util.*;
23+
24+
public class Solution {
25+
public static int PairSum(int[] input, int size) {
26+
/* Your class should be named Solution
27+
* Don't write main().
28+
* Don't read input, it is passed as function argument.
29+
* Return output and don't print it.
30+
* Taking input and printing output is handled automatically.
31+
*/
32+
if (size==0)
33+
return 0;
34+
35+
HashMap<Integer,Integer> map = new HashMap<>();
36+
for(int key:input)
37+
{
38+
if(map.containsKey(key))
39+
{
40+
map.put(key,map.get(key)+1);
41+
}
42+
else
43+
{
44+
map.put(key,1);
45+
}
46+
}
47+
/*
48+
for (Integer i: map.keySet())
49+
{
50+
System.out.println(i + ": " + map.get(i));
51+
}
52+
System.out.println();
53+
*/
54+
int countPairs=0;
55+
for (Integer i: map.keySet())
56+
{
57+
if (map.containsKey(-i) && i!=0)
58+
{
59+
//System.out.println("Found the negative of " + i);
60+
countPairs=countPairs+(map.get(i)*map.get(-i));
61+
//System.out.println("Current count of pairs: "+countPairs);
62+
//map.remove(i);
63+
}
64+
//System.out.println();
65+
}
66+
countPairs=countPairs/2;
67+
if (map.containsKey(0))
68+
{
69+
int val=map.get(0);
70+
countPairs=countPairs+(val*(val-1))/2;
71+
}
72+
return countPairs;
73+
}
74+
}

0 commit comments

Comments
 (0)