Two Pointer Method
In this approach we use two pointer to find if the target value exist in the array or not. We will use two pointer left and right initialized with the value of 0 and n-1 respectively. We will traverse until left pointer crosses the right pointer and find if the pair with sum value equal to target exist. If the pair exist then we will return true else return false.
Below steps to implement above approach
- Sort the array.
- Initialize the two pointers left and right , with left = 0 and right = n-1.
- Traverse the loop until left crosses right.
- If any pair with sum equal to target value exist , return true.
- else return false.
Example: This example implements the above-mentioned approach.
Javascript
function twoSum(n, arr, target) { arr.sort((a, b) => a - b); let left = 0, right = n - 1; while (left < right) { const sum = arr[left] + arr[right]; if (sum === target) { return "True" ; } else if (sum < target) { left++; } else { right--; } } return "False" ; } function main() { const n = 5; const arr = [3, 6, 4, 8, 7]; const target = 10; const ans = twoSum(n, arr, target); console.log(ans); } main(); |
True
Check if Pair with given Sum Exists in Array using JavaScript
We will check if a pair with a given Sum exists in an Array or not using JavaScript.