Skip to content

Commit 8bde9b9

Browse files
Feat: TwoSum function created with test cases
1 parent bdf8ed8 commit 8bde9b9

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Maths/TwoSum.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
Given an array of integers, return indices of the two numbers such that they add up to
3+
a specific target.
4+
5+
You may assume that each input would have exactly one solution, and you may not use the
6+
same element twice.
7+
8+
Example
9+
Given nums = [2, 7, 11, 15], target = 9,
10+
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
11+
return [0, 1].
12+
*/
13+
14+
const TwoSum = (nums, target) => {
15+
const numIndicesMap = {}
16+
for (let i = 0; i < nums.length; i++) {
17+
const complement = target - nums[i]
18+
if (complement in numIndicesMap) return [numIndicesMap[complement], i]
19+
numIndicesMap[nums[i]] = i
20+
}
21+
return []
22+
}
23+
export { TwoSum }

0 commit comments

Comments
 (0)