Solution: Two Sum

You’re given an array of integers. Write a function that returns a pair of numbers such that they sum up to zero.

Image for post
Image for post
[Alternate problem with a target]
Array of integers is [2, 7, 9, -2].
The pair that sums up to 0 is (2, -2).
2 7 9 -2
-2 2

Solution:

Observe

Algorithm

Code

/**
* @param {Array<Number>} nums
* @param {Array<Number>} 2 numbers from nums that add up to 0.
*/
function pairOfZeroSum(nums) {
const hashmap = new Map();
for (let i = 0; i < nums.length; i++) {
if (hashmap.has(-nums[i])) {
return [nums[i], -nums[i]];
}
hashmap.set(nums[i], true);
}
// We should not reach this point since a solution is guaranteed
// to exist.
return [];
}

Complexity Analysis

Written by

Software Engineer @Vedantu, Former Intern @Hackerrank, GSoC @Wikimedia, Former Intern @Vedantu, Codeforces(Expert)

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