Given a list of integers return all the pairs that makes up to a given target sum.
input:
{2, 7, 11, 15, -2}
target sum:9
This should return all the pairs i.e
{-2,11} and {7,2}
.If there are duplicates that form the same pair, they should not be returned.
Here is the code for this problem - would be great to know how this can be refactored for improvement.
public class TwoSum {
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof Pair) {
Pair other = (Pair) o;
if (other.x == this.x && other.y == this.y) {
return true;
}
}
return false;
}
@Override
public String toString() {
return new StringBuilder().append("{").append(this.x).append(",").append(this.y).append("}").toString();
}
}
public static Set<Pair> findPairs(int inputs[], int targetSum) {
Set<Pair> results = new HashSet<>();
Map<Integer, Integer> map = new HashMap<>();
for (int number : inputs) {
int remainingSum = targetSum - number;
if (map.containsKey(number)) {
results.add(new Pair(number, map.get(number)));
} else {
map.put(remainingSum, number);
}
}
return results;
}
To invoke this code:
System.out.println(TwoSum.findPairs(new int[]{2, 7, 11, 15, -2}, 9));
This would print:
[{-2,11}, {7,2}]
Code here:
https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/TwoSum.java