-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoPointer.js
More file actions
32 lines (23 loc) · 730 Bytes
/
twoPointer.js
File metadata and controls
32 lines (23 loc) · 730 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
//Two Pointer technique
//Strings and arrays benefit largely from this techique
//This technique is helpful when we have to analyze
//each element of the collection compared to its other elements
//As a result we can process two elements per loop instead of one
//Two Sum probelem
const arr = [1,2,3,5,6,7,8];
const target = 5;
const twoSum = function(arr, t) {
let pointer1 = 0;
let pointer2 = arr.length - 1;
while (pointer1 < pointer2) {
const sum = arr[pointer1] + arr[pointer2];
if (sum == t) {
return [pointer1, pointer2];
} else if (sum < target) {
pointer1++;
} else {
pointer2--;
}
}
}
console.log(twoSum(arr, target));