Two Pointers : Pattern for Coding Questions

Hack the coding interviews at FAANG!

Question at FAANG interviews: Pair with Target Sum

Input: arr = [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The numbers at indices 1 and 3 add up to 6: 2+4=6

Solution 1 : We can follow the Two Pointers approach.

function pair_with_target_sum(arr, targetSum) {let left = 0,right = arr.length - 1;while (left < right) {const currentSum = arr[left] + arr[right];if (currentSum === targetSum) {return [left, right];}
if (targetSum > currentSum) {left += 1; // we need a pair with a bigger sum} else {right -= 1; // we need a pair with a smaller sum}}return [-1, -1];}

Solution 2 : using HashTable

function pair_with_target_sum(arr, targetSum) {const nums = {}; // HashTable to store numbers and their indicesfor (let i = 0; i < arr.length; i++) {const num = arr[i];if (targetSum - num in nums) {return [nums[targetSum - num], i];}nums[arr[i]] = i;}return [-1, -1];}

--

--

Web Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store