├── README.md └── method.js /README.md: -------------------------------------------------------------------------------- 1 | # pointer 2 | JavaScript script that demonstrates the two pointers method to find if there are two numbers in a sorted array that add up to a specific target sum 3 | -------------------------------------------------------------------------------- /method.js: -------------------------------------------------------------------------------- 1 | function twoSum(nums, target) { 2 | let left = 0; 3 | let right = nums.length - 1; 4 | 5 | while (left < right) { 6 | const sum = nums[left] + nums[right]; 7 | if (sum === target) { 8 | return [nums[left], nums[right]]; 9 | } else if (sum < target) { 10 | left++; 11 | } else { 12 | right--; 13 | } 14 | } 15 | 16 | return null; // If no such pair exists 17 | } 18 | 19 | // Example usage: 20 | const nums = [1, 2, 3, 4, 5, 6, 7]; 21 | const target = 10; 22 | const result = twoSum(nums, target); 23 | if (result) { 24 | console.log(`Pair with sum ${target} found: [${result[0]}, ${result[1]}]`); 25 | } else { 26 | console.log(`No pair found with sum ${target}`); 27 | } 28 | --------------------------------------------------------------------------------