Skip to content

Commit 1de5ab7

Browse files
Feat: TwoSum function created with test cases (TheAlgorithms#1399)
* fix: TheAlgorithms#758 optimised armstrongNumber code * fix:TheAlgorithms#758 Average Median code optimised * feat: TwoSum function added with test cases * revert code * Fix: TheAlgorithms#758 used ternary operator to make code more optimised * Feat: TwoSum function created with test cases * Feat: TwoSum function created with test cases * Resolved comments and changes requests
1 parent 86d333e commit 1de5ab7

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Maths/TwoSum.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Given an array of integers, find two numbers that add up to a specific target.
3+
*
4+
* @param {number[]} nums - The array of integers.
5+
* @param {number} target - The target sum.
6+
* @returns {number[]} - An array containing the indices of the two numbers.
7+
*
8+
* @example
9+
* const nums = [2, 7, 11, 15];
10+
* const target = 9;
11+
* const result = twoSum(nums, target);
12+
* // The function should return [0, 1] because nums[0] + nums[1] = 2 + 7 = 9.
13+
*/
14+
15+
const TwoSum = (nums, target) => {
16+
const numIndicesMap = new Map()
17+
for (let i = 0; i < nums.length; i++) {
18+
const complement = target - nums[i]
19+
if (numIndicesMap.has(complement)) return [numIndicesMap.get(complement), i]
20+
numIndicesMap.set(nums[i], i)
21+
}
22+
return []
23+
}
24+
export { TwoSum }

Maths/test/TwoSum.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { TwoSum } from '../TwoSum.js'
2+
describe('Two Sum', () => {
3+
const testCasesWithoutSolution = [
4+
[[8], 8],
5+
[[3, 3, 3, 3], 19]
6+
]
7+
const testCasesWithSolution = [
8+
[[2, 7, 11, 15], 9, [0, 1]],
9+
[[15, 2, 11, 7], 13, [1, 2]],
10+
[[2, 7, 11, 15], 17, [0, 3]],
11+
[[7, 15, 11, 2], 18, [0, 2]],
12+
[[2, 7, 11, 15], 26, [2, 3]]
13+
]
14+
15+
test.each(testCasesWithoutSolution)(
16+
'Should return an empty array if there is no solution',
17+
(nums, target) => {
18+
expect(TwoSum(nums, target)).toEqual([])
19+
}
20+
)
21+
22+
test.each(testCasesWithSolution)(
23+
'Should return the indices of two numbers that add up to the target',
24+
(nums, target, expected) => {
25+
expect(TwoSum(nums, target)).toEqual(expected)
26+
}
27+
)
28+
})

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