## Description

https://leetcode.com/problems/two-sum/

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].

## Explanation

The question is about finding two elements in an array that they add up to a given target.

There is a better way to solve the problem. We can introduce a HashMap to reduce time complexity. The HashMap stores visited element values and indexes. Every time we visit an element, we store the element value and index into the HashMap, and we check if the current element’s complement already exists in the HashMap. If the complement exists, we find a solution. The solution is efficient. Time Complexity is O(N).

## Java Solution

```
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> visited = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (visited.containsKey(target - nums[i])) {
result[0] = visited.get(target - nums[i]);
result[1] = i;
return result;
}
visited.put(nums[i], i);
}
return result;
}
}
```

## Python Solution

```
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
result = []
visited = {}
for i, num in enumerate(nums):
complement = target - num
if complement not in visited:
visited[num] = i
else:
result.append(i)
result.append(visited[complement])
return result
```

This is *time* efficient but not *space* efficient. If we are not permitted to use extra space then sorting in place and using pointers is an O(nlogn) solution.

Hey There,

I really like your video tutorial. Would you be interested in teaching on 1:1 basis.

Please WhatsApp(+1917-345-0459 or email aarjay4001@gmail.com

Thanks man Pls resolve this coding question ..https://leetcode.com/discuss/interview-question/242538/parking-car-problem-with-empty-spat