How to solve Two-Sum Algorithm in JavaScript
I think we all can agree on this: Two-Sum Algorithm is sort of a classic data structure challenge. In my blog, I’d like to share two approaches to solving it. The first one is a so-called “brute force” method, and the second one represents a more elegant solution
So, our problem is: Given an array of numbers and a target number, find the sum of two numbers from the array that is equal to the target number. May not sum the same index twice. Return these numbers.
- Create a working solution with nested loops (Time complexity: O(n²))
Here, I’m using nested for-loops to check all possible sums in the array. Once I get the right pair, I return them. If nothing matches, an empty array is returned.
function twoSum(nums, target) {
let result = [];
for(let i = 0; i < nums.length; i++) {
for(let j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] === target) {
result.push(nums[i], nums[j])
}
}
}
return result;
};
2. Use an Object-based solution (Time coxplexity: O(n))
A more sophisticated and time complexity friendly approach is solving this problem by using an empty object. That will give us O(n) in time complexity.
function twoSum(nums, target){
//FIRST STEP: create an empty Object
let numObject = {}
//SECOND STEP: use a for-loop to iterate through the array
for(let eachNum in nums){
let otherNum = target - nums[eachNum] //we'll check for otherNum in the object and if it's there, we got it and can push in our result array. if(otherNum in numObject){
let resultArr = [];
resultArr.push(otherNum, nums[eachNum])
return resultArr;
} numObject[nums[eachNum]] = eachNum//NB! adding key/value has to go after the if-statement to avoid adding the same index twice. We add the value or a new pair on each iteration.
}
return "not found";
}
Hope it was helpful!
Source: