From 1de5ab7d71d0241ec1903f54d96c9924ab912d2b Mon Sep 17 00:00:00 2001 From: Ayush shah Date: Wed, 4 Oct 2023 09:59:01 +0530 Subject: [PATCH] Feat: TwoSum function created with test cases (#1399) * fix: #758 optimised armstrongNumber code * fix:#758 Average Median code optimised * feat: TwoSum function added with test cases * revert code * Fix: #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 --- Maths/TwoSum.js | 24 ++++++++++++++++++++++++ Maths/test/TwoSum.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 Maths/TwoSum.js create mode 100644 Maths/test/TwoSum.test.js diff --git a/Maths/TwoSum.js b/Maths/TwoSum.js new file mode 100644 index 000000000..8aaaea9d1 --- /dev/null +++ b/Maths/TwoSum.js @@ -0,0 +1,24 @@ +/** + * Given an array of integers, find two numbers that add up to a specific target. + * + * @param {number[]} nums - The array of integers. + * @param {number} target - The target sum. + * @returns {number[]} - An array containing the indices of the two numbers. + * + * @example + * const nums = [2, 7, 11, 15]; + * const target = 9; + * const result = twoSum(nums, target); + * // The function should return [0, 1] because nums[0] + nums[1] = 2 + 7 = 9. + */ + +const TwoSum = (nums, target) => { + const numIndicesMap = new Map() + for (let i = 0; i < nums.length; i++) { + const complement = target - nums[i] + if (numIndicesMap.has(complement)) return [numIndicesMap.get(complement), i] + numIndicesMap.set(nums[i], i) + } + return [] +} +export { TwoSum } diff --git a/Maths/test/TwoSum.test.js b/Maths/test/TwoSum.test.js new file mode 100644 index 000000000..851f180a9 --- /dev/null +++ b/Maths/test/TwoSum.test.js @@ -0,0 +1,28 @@ +import { TwoSum } from '../TwoSum.js' +describe('Two Sum', () => { + const testCasesWithoutSolution = [ + [[8], 8], + [[3, 3, 3, 3], 19] + ] + const testCasesWithSolution = [ + [[2, 7, 11, 15], 9, [0, 1]], + [[15, 2, 11, 7], 13, [1, 2]], + [[2, 7, 11, 15], 17, [0, 3]], + [[7, 15, 11, 2], 18, [0, 2]], + [[2, 7, 11, 15], 26, [2, 3]] + ] + + test.each(testCasesWithoutSolution)( + 'Should return an empty array if there is no solution', + (nums, target) => { + expect(TwoSum(nums, target)).toEqual([]) + } + ) + + test.each(testCasesWithSolution)( + 'Should return the indices of two numbers that add up to the target', + (nums, target, expected) => { + expect(TwoSum(nums, target)).toEqual(expected) + } + ) +})