Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 9 additions & 16 deletions solutions/javascript/array-pair-sum.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
module.exports = function (k, array) {
var hash = {},
pairs = [];
module.exports = function (sum, array) {
var results = [];

// Loop through the array once, storing the results in an object for a
// time complexity of O(n) - the naive solution consists of two for loops
// which results in a complexity of O(n^2)
array.forEach(function (number) {
// Make sure the value in unused and it's a unique pair
if (hash[k - number] === false && k - number !== number) {
pairs.push([number, k - number]);
hash[k - number] = true; // Set it to "used"
for (var i = 0, len = array.length; i < len; i++) {
for (var j = i + 1; j < len; j++) {
if (array[i] + array[j] === sum) {
results.push([array[i], array[j]]);
}
}
}

// If the hash value is not true, set the hash to "unused"
!hash[k - number] && (hash[number] = false);
});

return pairs;
return results;
};
12 changes: 12 additions & 0 deletions tests/javascript/array-pair-sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var expect = require('chai').expect;
var arrayPairSum = require('../../solutions/javascript/array-pair-sum');

describe('Array Pair Sum', function () {
it('should find pairs that equal the expected sum', function () {
expect(arrayPairSum(10, [3, 4, 5, 6, 7])).to.eql([[3, 7], [4, 6]]);
});

it('should allow for duplicate results', function () {
expect(arrayPairSum(8, [3, 4, 5, 4, 4])).to.eql([[3, 5], [4, 4], [4, 4], [4, 4]]);
});
});