🟢 Easy 🧩 Pattern – Arrays and Hashmap
Given an array of distinct integers and a target sum, return an array of unique pairs of numbers which add up to the target sum. Each pair should be represented as an array containing only two numbers.
Example
Input : [2, 4, 3, 6, 7, 1, 5]
TargetSum : 8
Output : [ [ 6, 2 ], [ 1, 7 ], [ 3, 5 ] ]Code language: CSS (css)Solution
function targetSumPairs(nums, target) {
const pairs = [];
const seen = new Set(); // Acts like a Hashmap
for (const num of nums) {
const diff = target - num;
if (seen.has(diff)) {
pairs.push([num, diff]);
} else {
seen.add(num);
}
}
return pairs;
}
const target = 8;
const nums = [2, 4, 3, 6, 7, 1, 5];
console.log(targetSumPairs(nums, target));
// [[6, 2], [1, 7], [5, 3]]
console.log(targetSumPairs([-1, -2, -3, 1, 2, 3], 0));
// Output: [ [ 1, -1 ], [ 2, -2 ], [ 3, -3 ] ]
console.log(targetSumPairs([1, 2, 3, 4, 5], 10));
// Output: []Code language: JavaScript (javascript)