Skip to content

Commit c1e8046

Browse files
Added the new algorithm TwoSum using array in Data Structure
1 parent 08d8c6b commit c1e8046

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

Data-Structures/Array/TwoSum.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* This function will accept an array and a target value,
3+
* and return the indexes of the two numbers that add up to the target.
4+
* If no such pair exists, it returns null.
5+
* @param {number[]} nums - array of numbers
6+
* @param {number} target - target sum
7+
* @returns {number[] | null} - array containing two indexes or null
8+
*/
9+
10+
const twoSum = (nums, target) => {
11+
for (let i = 0; i < nums.length; i++) {
12+
for (let j = i + 1; j < nums.length; j++) {
13+
if (nums[i] + nums[j] === target)
14+
return [i, j]
15+
}
16+
}
17+
return null
18+
}
19+
20+
export { twoSum }
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { twoSum } from '../TwoSum'
2+
3+
describe('twoSum tests', () => {
4+
it('should return indices for a normal case', () => {
5+
const nums = [2, 7, 11, 15]
6+
const target = 9
7+
expect(twoSum(nums, target)).toEqual([0, 1])
8+
})
9+
10+
it('should return indices when pair is in middle', () => {
11+
const nums = [1, 4, 6, 8, 5]
12+
const target = 11
13+
expect(twoSum(nums, target)).toEqual([2, 4])
14+
})
15+
16+
it('should handle negative numbers', () => {
17+
const nums = [-3, 4, 3, 90]
18+
const target = 0
19+
expect(twoSum(nums, target)).toEqual([0, 2])
20+
})
21+
22+
it('should return null if no pair found', () => {
23+
const nums = [1, 2, 3, 4]
24+
const target = 100
25+
expect(twoSum(nums, target)).toBeNull()
26+
})
27+
28+
it('should work with duplicate numbers', () => {
29+
const nums = [3, 3]
30+
const target = 6
31+
expect(twoSum(nums, target)).toEqual([0, 1])
32+
})
33+
})

0 commit comments

Comments
 (0)