Skip to content

Commit b8be2f9

Browse files
feat: TwoSum function added with test cases
1 parent 184ae84 commit b8be2f9

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-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 }

Maths/test/TwoSum.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { TwoSum } from '../TwoSum.js'
2+
3+
describe('Two Sum', () => {
4+
it('Should find the indices of two numbers that add up to the target', () => {
5+
expect(TwoSum([2, 7, 11, 15], 9)).toEqual([0, 1])
6+
expect(TwoSum([15, 2, 11, 7], 13)).toEqual([1, 2])
7+
expect(TwoSum([2, 7, 11, 15], 17)).toEqual([0, 3])
8+
expect(TwoSum([7, 15, 11, 2], 18)).toEqual([0, 2])
9+
expect(TwoSum([2, 7, 11, 15], 26)).toEqual([2, 3])
10+
expect(TwoSum([2, 7, 11, 15], 8)).toEqual([])
11+
expect(
12+
TwoSum(
13+
[...Array(10).keys()].map((i) => 3 * i),
14+
19
15+
)
16+
).toEqual([])
17+
})
18+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy