Skip to content

Commit 3152f14

Browse files
authored
Merge pull request vJechsmayr#93 from caleywoods/two-sum-linear
linear two-sum solution
2 parents 0b1ba90 + 580aa8c commit 3152f14

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

OtherAlgorithms/two-sum-linear.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// O(n) time Solution to https://leetcode.com/problems/two-sum/
2+
const twoSum = (nums, target) => {
3+
const seen = new Map();
4+
5+
// store complement as key and the index as the value
6+
for (let i = 0; i < nums.length; i++) {
7+
const complement = target - nums[i];
8+
9+
if (seen.has(complement)) {
10+
return [seen.get(complement), i];
11+
}
12+
seen.set(nums[i], i);
13+
}
14+
};
15+
16+
// twoSum([2,7,11,15], 9); // should return [0,1]
17+
// twoSum([3,3], 6); // should return [0,1]
18+
// twoSum([4,1,2,13,9,51], 53); // should return [2, 5]

0 commit comments

Comments
 (0)