Two Sum
ref: https://leetcode.com/problems/two-sum/
const twoSum = (nums, target) => {
const map = new Map()
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i]
if (map.has(complement) && map.get(complement) !== i) {
return [i, map.get(complement)]
}
map.set(nums[i], i)
}
}
the above is the final solution as described by the author of the leetcode question.
Here are some use cases that could possibly make use of the algorithm
- organizing debit/credit card payments + refunds:
- input your target price, and it will find the two transactions that match
- with a bit of work, it could be used to find complementary vectors in a vector embedding