-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindTwoSum.js
More file actions
35 lines (31 loc) · 734 Bytes
/
Copy pathfindTwoSum.js
File metadata and controls
35 lines (31 loc) · 734 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'use strict';
/**
* Given an array of integers and a value, find a pair
* of integers in the array that add to that value.
*
* Example:
* input: ( [1,-2,4,2,6], 8 )
* output: [2, 6]
*/
/**
* Return a pair of values from array that add to value.
* Null if no such values exist.
*
* @export
* @param {*} arr
* @param {*} value
*/
const findTwoSum = (arr, value) => {
if (!Array.isArray(arr) || typeof value !== 'number') return null;
const pastVals = {};
for (let i = 0; i < arr.length; i++) {
const neededValue = value - arr[i];
if (neededValue in pastVals) {
return [neededValue, arr[i]];
} else {
pastVals[arr[i]] = i;
}
}
return null;
};
module.exports = findTwoSum;