Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Data-Structures/Array/TwoSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* This function will accept an array and a target value,
* and return the indexes of the two numbers that add up to the target.
* If no such pair exists, it returns null.
* @param {number[]} nums - array of numbers
* @param {number} target - target sum
* @returns {number[] | null} - array containing two indexes or null
*/

const twoSum = (nums, target) => {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target)
return [i, j]
}
}
return null
}

export { twoSum }
33 changes: 33 additions & 0 deletions Data-Structures/Array/test/TwoSum.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { twoSum } from '../TwoSum'

describe('twoSum tests', () => {
it('should return indices for a normal case', () => {
const nums = [2, 7, 11, 15]
const target = 9
expect(twoSum(nums, target)).toEqual([0, 1])
})

it('should return indices when pair is in middle', () => {
const nums = [1, 4, 6, 8, 5]
const target = 11
expect(twoSum(nums, target)).toEqual([2, 4])
})

it('should handle negative numbers', () => {
const nums = [-3, 4, 3, 90]
const target = 0
expect(twoSum(nums, target)).toEqual([0, 2])
})

it('should return null if no pair found', () => {
const nums = [1, 2, 3, 4]
const target = 100
expect(twoSum(nums, target)).toBeNull()
})

it('should work with duplicate numbers', () => {
const nums = [3, 3]
const target = 6
expect(twoSum(nums, target)).toEqual([0, 1])
})
})
Loading