Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit 614de5c

Browse files
committed
Adding extra clause to the array pair sum solution.
1 parent 0bc8b38 commit 614de5c

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

array-pair-sum/Readme.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
Given an integer array, output all pairs that sum up to a specific value k. Consider the fact that the same number can add up to `k` with its duplicates in the array.
44

5+
> For example the array is [1, 1, 2, 3, 4] and the desired sum is 4. Should we output the pair (1, 3) twice or just once? Also do we output the reverse of a pair, meaning both (3, 1) and (1, 3)? Let’s keep the output as short as possible and print each pair only once. So, we will output only one copy of (1, 3). Also note that we shouldn’t output (2, 2) because it’s not a pair of two distinct elements.
6+
57
## Example
68

79
```
@@ -11,4 +13,4 @@ f(8, [3, 4, 5, 4, 4]) // [ [3, 5], [4, 4], [4, 4], [4, 4] ]
1113

1214
## Source
1315

14-
[http://www.ardendertat.com/2012/01/09/programming-interview-questions/](http://www.ardendertat.com/2012/01/09/programming-interview-questions/)
16+
[http://www.ardendertat.com/2011/09/17/programming-interview-questions-1-array-pair-sum/](http://www.ardendertat.com/2011/09/17/programming-interview-questions-1-array-pair-sum/)

array-pair-sum/array-pair-sum.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@ var arrayPairSum = function (k, array) {
77
// time complexity of O(n) - the naive solution consists of two for loops
88
// which results in a complexity of O(n^2)
99
array.forEach(function (number) {
10-
for (var i = 0; i < hash[k - number]; i++) {
10+
// Make sure the value in unused and it's a unique pair
11+
if (hash[k - number] === false && k - number !== number) {
1112
pairs.push([number, k - number]);
13+
hash[k - number] = true; // Set it to "used"
1214
}
1315

14-
hash[number] = hash[number] + 1 || 1;
16+
// If the hash value is not true, set the hash to "unused"
17+
!hash[k - number] && (hash[number] = false);
1518
});
1619

1720
return pairs;

0 commit comments

Comments
 (0)