Skip to content
Closed
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
25 changes: 25 additions & 0 deletions src/_Problems_/two-sum/index.js
Original file line number Diff line number Diff line change
@@ -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 };
11 changes: 11 additions & 0 deletions src/_Problems_/two-sum/two-sum.test.js
Original file line number Diff line number Diff line change
@@ -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]);
});
});