From 450c2fa289eb93bc791d4b6f47fcff5c7f59a3ec Mon Sep 17 00:00:00 2001 From: SHEEVOOT Date: Fri, 11 Oct 2019 17:12:37 +0530 Subject: [PATCH] Added Two Sum problem --- README.md | 1 + src/_Problems_/two-sum/index.js | 25 +++++++++++++++++++++++++ src/_Problems_/two-sum/two-sum.test.js | 11 +++++++++++ 3 files changed, 37 insertions(+) create mode 100644 src/_Problems_/two-sum/index.js create mode 100644 src/_Problems_/two-sum/two-sum.test.js diff --git a/README.md b/README.md index fd888d40..944bb70e 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct - [Reverse String](src/_Problems_/reverse_string) - [Maximum Product of Three Numbers](src/_Problems_/max-product-of-3-numbers) - [Next Greater for Every Element in an Array](src/_Problems_/next-greater-element) +- [Two Sum](src/_Problems_/two-sum) ### Searching diff --git a/src/_Problems_/two-sum/index.js b/src/_Problems_/two-sum/index.js new file mode 100644 index 00000000..06dbfb44 --- /dev/null +++ b/src/_Problems_/two-sum/index.js @@ -0,0 +1,25 @@ +/* +Two Sum Problem +Given an array of integers, return indices of the two numbers such that they add up to a specific target. +You may assume that each input would have exactly one solution, and you may not use the same element twice. + +Example: +Given nums = [2, 7, 11, 15], target = 9, +Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1]. + +Solved in O(n) time complexity using Hash/Object +*/ + +function twoSum(nums, target) { + const numsHash = {}; + for (let i = 0; i < nums.length; i++) { + const difference = target - nums[i]; + if (numsHash[difference] !== undefined) { + return [numsHash[difference], i]; + } + numsHash[nums[i]] = i; + } +}; + +module.exports = { twoSum }; \ No newline at end of file diff --git a/src/_Problems_/two-sum/two-sum.test.js b/src/_Problems_/two-sum/two-sum.test.js new file mode 100644 index 00000000..6af61e4e --- /dev/null +++ b/src/_Problems_/two-sum/two-sum.test.js @@ -0,0 +1,11 @@ +const { twoSum } = require('.'); + +describe('Two Sum', () => { + it('Should return a index of elements added to get target', () => { + expect(twoSum([2, 7, 11, 15], 9)).toEqual([0, 1]); + }); + + it('Should return a index of elements added to get target', () => { + expect(twoSum([8, -4, 2, 14, 11, 17], 7)).toEqual([1, 4]); + }); +});