## 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:**

1 2 3 4 |
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 the given target.

Simply, we can use a nested loop to solve the problem. We have an **i** variable to visit each element and we have another variable **j** to check if there is another value that equals to **$]$**. The idea is easy. However, the solution is not efficient. The time complexity would be **O(N²****)**.

There is a better way to solve the problem. We introduce a HashMap. We stored visited elements values and indexes into the HashMap. Every time we visit an element, we store the element value and index into the HashMap, and we check if 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)**.

## Video Tutorial

## Java Solution

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; HashMap<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; } } |

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