Skip to content

Commit 3810e50

Browse files
committed
Two Sum solution
1 parent bb0db1a commit 3810e50

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

two-sum/kimyoung.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
var twoSum = function (nums, target) {
2+
let map = new Map(); // create a map to store the number and index of each element
3+
for(let i = 0; i < nums.length; i++) {
4+
let diff = target - nums[i];
5+
if(map.has(diff)) { // once the differnece is found, return both index
6+
return [i, map.get(diff)];
7+
} else { // otherwise add to map
8+
map.set(nums[i], i)
9+
}
10+
}
11+
};
12+
13+
// time - O(n) at worst, iterate through the entire nums array
14+
// space - O(n) at worst, map the entire nums array

0 commit comments

Comments
 (0)