1
+ package com .rampatra .arrays ;
2
+
3
+ import java .util .HashSet ;
4
+ import java .util .Set ;
5
+
6
+ /**
7
+ * Level: Easy
8
+ * Problem Description:
9
+ * Given an array and a target sum, return the number of distinct pairs whose sum is equal to the target sum.
10
+ * <p>
11
+ * For Example, given an array [1, 2, 3, 6, 7, 8, 9, 1] and a target sum of 10,
12
+ * the 7 pairs, i.e, (1, 9), (2, 8), (3, 7), (8, 2), (9, 1), (9, 1), and (1, 9) all sum to 10 but there are only
13
+ * three distinct pairs, i.e, (1, 9), (2, 8), and (3, 7) so the answer would be 3.
14
+ *
15
+ * @author rampatra
16
+ * @since 2019-06-03
17
+ */
18
+ public class DistinctPairs {
19
+
20
+ /**
21
+ * Time complexity: O(n), n = size of the array
22
+ * Space complexity: O(n)
23
+ *
24
+ * @param arr
25
+ * @param targetSum
26
+ * @return
27
+ */
28
+ private static int numberOfDistinctPairs (int [] arr , int targetSum ) {
29
+ Set <Integer > numSet = new HashSet <>();
30
+ Set <Set <Integer >> pairSet = new HashSet <>();
31
+
32
+ for (int i = 0 ; i < arr .length ; i ++) {
33
+ if (numSet .contains (targetSum - arr [i ])) {
34
+ Set <Integer > pair = new HashSet <>();
35
+ pair .add (arr [i ]);
36
+ pair .add (targetSum - arr [i ]);
37
+ pairSet .add (pair );
38
+ }
39
+ numSet .add (arr [i ]);
40
+ }
41
+
42
+ return pairSet .size ();
43
+ }
44
+
45
+ public static void main (String [] args ) {
46
+ System .out .println (numberOfDistinctPairs (new int []{1 , 2 , 3 , 6 , 7 , 8 , 9 , 1 }, 1 ));
47
+ System .out .println (numberOfDistinctPairs (new int []{1 , 2 , 3 , 6 , 7 , 8 , 9 , 1 }, 2 ));
48
+ System .out .println (numberOfDistinctPairs (new int []{1 , 2 , 3 , 6 , 7 , 8 , 9 , 1 }, 10 ));
49
+ }
50
+ }
0 commit comments