From c1e80464d426903402ab25fa02d951321f51f6f7 Mon Sep 17 00:00:00 2001 From: Rakshita R Mirji Date: Wed, 5 Nov 2025 17:36:57 +0530 Subject: [PATCH] Added the new algorithm TwoSum using array in Data Structure --- Data-Structures/Array/TwoSum.js | 20 ++++++++++++++ Data-Structures/Array/test/TwoSum.test.js | 33 +++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 Data-Structures/Array/TwoSum.js create mode 100644 Data-Structures/Array/test/TwoSum.test.js diff --git a/Data-Structures/Array/TwoSum.js b/Data-Structures/Array/TwoSum.js new file mode 100644 index 0000000000..6700c2f084 --- /dev/null +++ b/Data-Structures/Array/TwoSum.js @@ -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 } diff --git a/Data-Structures/Array/test/TwoSum.test.js b/Data-Structures/Array/test/TwoSum.test.js new file mode 100644 index 0000000000..d23565cf7b --- /dev/null +++ b/Data-Structures/Array/test/TwoSum.test.js @@ -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]) + }) +})