|
| 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. |
0 commit comments