JavaScript: Two sum problem
Hari Krishna Anem
1 min read
Table of contents
let startTime, endTime
let integerArr = [1, 2, 8, 4, 5, 18];
let targetNum = 19;
function twoSumMethod1 (integerArr, targetNum) {
let condition = false;
for (let i = 0; i < integerArr.length; i++) {
for (let j = 0; j < integerArr.length; j++) {
if (integerArr[i] === integerArr[j]) continue;
if (integerArr[i] + integerArr[j] === targetNum && !condition) {
condition = true;
return [i, j];
}
}
}
}
startTime = performance.now()
console.log(twoSumMethod1 (integerArr, targetNum));
endTime = performance.now()
console.log(`Method 1 took ${endTime - startTime} milliseconds`)
console.log(`--------------------------------------------`);
function twoSumMethod2 (integerArr, targetNum) {
let vals = {};
for (let i = 0; i < integerArr.length; i++) {
if (targetNum - integerArr[i] in vals) {
return [vals[targetNum-integerArr[i]], i];
}
else {
vals[integerArr[i]] = i;
}
}
return [];
};
startTime = performance.now()
console.log(twoSumMethod2 (integerArr, targetNum));
endTime = performance.now()
console.log(`Method 2 took ${endTime - startTime} milliseconds`)
Output:
[ 0, 5 ]
Method 1 took 6.121358007192612 milliseconds
--------------------------------------------
[ 0, 5 ]
Method 2 took 0.21461999416351318 milliseconds
0
Subscribe to my newsletter
Read articles from Hari Krishna Anem directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Hari Krishna Anem
Hari Krishna Anem
Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)