File tree Expand file tree Collapse file tree 1 file changed +9
-11
lines changed Expand file tree Collapse file tree 1 file changed +9
-11
lines changed Original file line number Diff line number Diff line change 1
- module . exports = function ( k , array ) {
1
+ module . exports = function arraypairsum ( k , array ) {
2
2
var hash = { } ;
3
3
var pairs = [ ] ;
4
4
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.
8
8
array . forEach ( function ( number ) {
9
- var target = k - number ;
9
+ var diff = k - number ;
10
+ var len = hash [ diff ] ;
10
11
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 ] ) ;
16
14
}
17
15
18
- hash [ number ] ++ ;
16
+ hash [ number ] = ( hash [ number ] + 1 ) || 1 ;
19
17
} ) ;
20
18
21
19
return pairs ;
You can’t perform that action at this time.
0 commit comments