Skip to content

Commit 98265a2

Browse files
committed
Correct array-pair-sum solution in JavaScript
1 parent eb878a9 commit 98265a2

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

solutions/javascript/array-pair-sum.js

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
1-
module.exports = function (k, array) {
1+
module.exports = function arraypairsum (k, array) {
22
var hash = {};
33
var pairs = [];
44

5-
// Loop through the array once, storing the results in an object for a
6-
// time complexity of O(n) - the naive solution consists of two for loops
7-
// which results in a complexity of O(n^2)
5+
// Iterate over the array, tracking the times each number appears. For each
6+
// new number, we calculate the difference to `k` and look up the number of
7+
// times that number has been seen and push those occurances in pairs output.
88
array.forEach(function (number) {
9-
var target = k - number;
9+
var diff = k - number;
10+
var len = hash[diff];
1011

11-
// Make sure the value in unused and it's a unique pair
12-
if (hash[target] === 1 && number + target === k) {
13-
pairs.push([target, number]);
14-
} else {
15-
hash[number] = 0;
12+
while (len--) {
13+
pairs.push([number, diff]);
1614
}
1715

18-
hash[number]++;
16+
hash[number] = (hash[number] + 1) || 1;
1917
});
2018

2119
return pairs;

0 commit comments

Comments
 (0)