### Leetcode 1. Two Sum

Two Sum

If you prefer video over text, watch this.

#### Thought Process

We want to find two numbers that add up to the target. Simple approach is to try out all pairs to check if they add up to the target. However, if you observe this process, once we fix one number, say `K`, then we know what the other number must be and i.e. `target-K`. For any other number, they won’t add up to the `target`. Now if we know that search is a vital operation, employ the best data structure for the search i.e. hash set. Because we want to return indices, use hash map instead.

#### Algorithm

1. Insert all elements with their indices in the map.
2. For each number, `K`
1. Check the map if `K` exists & return the indices if it does.
3. Return empty response because there is no such pair.

#### Code

 class Solution { public: vector twoSum(vector& nums, int target) { unordered_map m; // To store the integer and its index. int n = nums.size(); // Total integers. for (int i=0; i
view raw Leetcode_1.cpp hosted with ❤ by GitHub

Is there anything that is still unclear? Let me know in the comments and I can elaborate further.

Don’t forget like & share the post, and subscribe to the blog to get notifications whenever solution to a new problem is added.

Happy Coding!

#### Similar Problems

Leetcode 15. 3Sum