leetcode/hash-table/TwoSum.java
Author: knasimCreated Aug 13, 2018Updated Jul 26, 2024
There is a better solution for the TwoSum problem than the hashmap solution. Sure hashmap is fine and meets the desired output. however it can be completely eliminated as such. The techinque employs a pointers to track the argument array i.e. one from the begining aka head and the other one from the end aka tail. A single sweep on the array and adjusting the two pointers does the job rather nicely.
//input array must be sorted
int head =0; int tail = arr.length -1; int k = 11; //target sum to find
while(head < tail) {
int sum = arr[head] + arr[tail];
if(sum == k) return true; //found it !!
else if(sum < k) ++head;
else --tail;
}
Source: kdn251/interviews