Skip to content

Commit f84cb57

Browse files
authored
Merge pull request #44 from khairalanam/khair
Add Two Sum Problem
2 parents 5cdcdfb + f3ac350 commit f84cb57

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

L-I/0009 TwoSum/README.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# 0009 TwoSum ( L-I )
2+
3+
## Problem
4+
5+
Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`.
6+
7+
## Testcases
8+
9+
- Input: `nums = [3, 2, 4], target = 6` <br>
10+
Output: `[1, 2]`
11+
12+
- Input: `nums = [2, 7, 11, 15], target = 9` <br>
13+
Output: `[0, 1]`
14+
15+
- Input: `nums = [3, 3], target = 6` <br>
16+
Output: `[0, 1]`
17+
18+
## Solution
19+
20+
```javascript
21+
const TwoSum = (nums, target) => {
22+
numToIndex = {};
23+
24+
for (let i = 0; i < nums.length; i++) {
25+
if (target - nums[i] in numToIndex)
26+
return [numToIndex[target - nums[i]], i];
27+
28+
numToIndex[nums[i]] = i;
29+
}
30+
31+
return [];
32+
};
33+
```
34+
35+
## How it works
36+
37+
- The functiont takes an array of integers `nums` and an integer `target`.
38+
- We initialise an object `numToIndex` to push the element and its index as key-value pairs.
39+
- The function runs a for loop for the length of `nums`.
40+
- If the difference of `target` and the current element at `i`th index is present in the keys of `numToIndex`, then return the array that contains the element corresponding to the difference as well as the current element.
41+
- If not present, then set the element at `i`th index to be equal to `i` for `numToIndex`.
42+
- If the for loop terminates normally, then return an empty array.
43+
44+
## References
45+
46+
- [LeetCode](https://leetcode.com/problems/two-sum/)
47+
48+
## Problem Added By
49+
50+
- [GitHub](https://www.github.com/khairalanam)
51+
- [LinkedIn](https://www.linkedin.com/in/khair-alanam-b27b69221/)
52+
- [Twitter](https://twitter.com/khair_alanam)
53+
54+
## Contributing
55+
56+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

L-I/0009 TwoSum/TwoSum.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const TwoSum = (nums, target) => {
2+
numToIndex = {};
3+
4+
for (let i = 0; i < nums.length; i++) {
5+
if (target - nums[i] in numToIndex)
6+
return [numToIndex[target - nums[i]], i];
7+
8+
numToIndex[nums[i]] = i;
9+
}
10+
11+
return [];
12+
};
13+
14+
nums = [3, 2, 4];
15+
target = 6;
16+
17+
nums1 = [2, 7, 11, 15];
18+
target1 = 9;
19+
20+
nums2 = [3, 3];
21+
target2 = 6;
22+
23+
console.log(TwoSum(nums, target));
24+
console.log(TwoSum(nums1, target1));
25+
console.log(TwoSum(nums2, target2));

0 commit comments

Comments
 (0)