Skip to content

Commit 8296ddb

Browse files
committed
Add two sum indices implementation
1 parent 633cf3b commit 8296ddb

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
function twoSumWithMap(arr, target) {
2+
if(arr.length < 2) return [];
3+
let numMap = new Map();
4+
for(let i=0; i < arr.length; i++) {
5+
let num = arr[i];
6+
let complement = target - num;
7+
if(numMap.has(complement)) {
8+
return [numMap.get(complement), i];
9+
}
10+
numMap.set(num, i);
11+
}
12+
return [];
13+
}
14+
15+
function twoSumWithObject(arr, target) {
16+
if(arr.length < 2) return [];
17+
let numObj = {};
18+
for(let i=0; i < arr.length; i++) {
19+
let num = arr[i];
20+
let complement = target - num;
21+
if(numObj.hasOwnProperty(complement)) {
22+
return [numObj[complement], i];
23+
}
24+
numObj[num] = i;
25+
}
26+
return [];
27+
}
28+
29+
30+
31+
32+
// Unique Numbers
33+
console.log("Input: [3, 4, 9, 14], Target: 12");
34+
console.log("Output: ", twoSumWithMap([3, 4, 9, 14], 12));
35+
36+
// Duplicate Numbers
37+
console.log("Input: [5, 7, 4, 7], Target: 14");
38+
console.log("Output: ", twoSumWithObject([5, 7, 4, 7], 14));
39+
40+
// No sum Numbers
41+
console.log("Input: [7, 1, 13, 1], Target: 10");
42+
console.log("Output: ", twoSumWithObject([7, 1, 13, 1], 10));
43+
44+
// Negative Numbers
45+
console.log("Input: [-5, -4, -3, -1, -2], Target: -10");
46+
console.log("Output: ", twoSumWithMap([-1, -2, -3, -4, -5], -10));
47+
48+
// One number Array
49+
console.log("Input: [3], Target: 4");
50+
console.log("Output: ", twoSumWithMap([3], 4));
51+
52+
// Empty Array
53+
console.log("Input: [], Target: 0");
54+
console.log("Output: ", twoSumWithObject([], 0));

0 commit comments

Comments
 (0)