Skip to content
Permalink
Newer
Older
100644 42 lines (38 sloc) 1022 Bytes
1
/***
2
*
3
* Given an array of sorted numbers and a target sum,
4
* find a pair in the array whose sum is equal to the given target.
5
*
6
Example 1:
7
Input: [1, 2, 3, 4, 6], target=6
8
Output: [1, 3]
9
Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6
10
11
Example 2:
12
Input: [2, 5, 9, 11], target=11
13
Output: [0, 2]
14
Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11
15
*
16
*
17
*/
18
19
function pairWithTargetSum(inputArr, target) {
20
var sum = 0
21
var result = []
22
var left = 0
23
var right = inputArr.length - 1
24
while(right > left){
25
sum = inputArr[left] + inputArr[right]
26
if(sum === target){
27
result.push(left, right)
28
}
29
if(sum > target){
30
right --
31
}else {
32
left ++
33
}
34
}
35
return result
36
}
37
38
let input = [1, 2, 3, 4, 6], target=6
39
let input1 = [2, 5, 9, 11], target1=11
40
41
console.log(`pair of target sum for ${input} with target ${target} is`, pairWithTargetSum(input, target))
42
console.log(`pair of target sum for ${input1} with target ${target1} is`, pairWithTargetSum(input1, target1))