# Two Sum
**Difficulty:** EASY
[External](https://leetcode.com/problems/two-sum)
Canonical: https://scaleengineer.com/dsa/problems/two-sum
**Data structures:** Array, Hash Table
**Companies:** [AMD](https://scaleengineer.com/companies/amd), [Accenture](https://scaleengineer.com/companies/accenture), [Accolite](https://scaleengineer.com/companies/accolite), [Adobe](https://scaleengineer.com/companies/adobe), [Agoda](https://scaleengineer.com/companies/agoda), [Airbnb](https://scaleengineer.com/companies/airbnb), [Airbus SE](https://scaleengineer.com/companies/airbus-se), [Akamai](https://scaleengineer.com/companies/akamai), [Altimetrik](https://scaleengineer.com/companies/altimetrik), [Amadeus](https://scaleengineer.com/companies/amadeus), [Amazon](https://scaleengineer.com/companies/amazon), [American Express](https://scaleengineer.com/companies/american-express), [Apple](https://scaleengineer.com/companies/apple), [Atlassian](https://scaleengineer.com/companies/atlassian), [Avito](https://scaleengineer.com/companies/avito), [BNY Mellon](https://scaleengineer.com/companies/bny-mellon), [Barclays](https://scaleengineer.com/companies/barclays), [BlackStone](https://scaleengineer.com/companies/blackstone), [Bloomberg](https://scaleengineer.com/companies/bloomberg), [Bolt](https://scaleengineer.com/companies/bolt), [Braze](https://scaleengineer.com/companies/braze), [ByteDance](https://scaleengineer.com/companies/bytedance), [Cadence](https://scaleengineer.com/companies/cadence), [Capgemini](https://scaleengineer.com/companies/capgemini), [Careem](https://scaleengineer.com/companies/careem), [Chewy](https://scaleengineer.com/companies/chewy), [Cisco](https://scaleengineer.com/companies/cisco), [Cognizant](https://scaleengineer.com/companies/cognizant), [Comcast](https://scaleengineer.com/companies/comcast), [Criteo](https://scaleengineer.com/companies/criteo), [Deloitte](https://scaleengineer.com/companies/deloitte), [Deutsche Bank](https://scaleengineer.com/companies/deutsche-bank), [Devsinc](https://scaleengineer.com/companies/devsinc), [Docusign](https://scaleengineer.com/companies/docusign), [DoorDash](https://scaleengineer.com/companies/doordash), [Dropbox](https://scaleengineer.com/companies/dropbox), [EPAM Systems](https://scaleengineer.com/companies/epam-systems), [EY](https://scaleengineer.com/companies/ey), [EarnIn](https://scaleengineer.com/companies/earnin), [Epic Systems](https://scaleengineer.com/companies/epic-systems), [Expedia](https://scaleengineer.com/companies/expedia), [FPT](https://scaleengineer.com/companies/fpt), [Fidelity](https://scaleengineer.com/companies/fidelity), [Flipkart](https://scaleengineer.com/companies/flipkart), [FreshWorks](https://scaleengineer.com/companies/freshworks), [Garmin](https://scaleengineer.com/companies/garmin), [Goldman Sachs](https://scaleengineer.com/companies/goldman-sachs), [Google](https://scaleengineer.com/companies/google), [Grab](https://scaleengineer.com/companies/grab), [HCL](https://scaleengineer.com/companies/hcl), [Honeywell](https://scaleengineer.com/companies/honeywell), [Huawei](https://scaleengineer.com/companies/huawei), [Hubspot](https://scaleengineer.com/companies/hubspot), [IBM](https://scaleengineer.com/companies/ibm), [Infosys](https://scaleengineer.com/companies/infosys), [Intel](https://scaleengineer.com/companies/intel), [Intuit](https://scaleengineer.com/companies/intuit), [J.P. Morgan](https://scaleengineer.com/companies/j.p.-morgan), [KLA](https://scaleengineer.com/companies/kla), [Karat](https://scaleengineer.com/companies/karat), [LinkedIn](https://scaleengineer.com/companies/linkedin), [Luxoft](https://scaleengineer.com/companies/luxoft), [Mastercard](https://scaleengineer.com/companies/mastercard), [Meta](https://scaleengineer.com/companies/meta), [Microsoft](https://scaleengineer.com/companies/microsoft), [MindTree](https://scaleengineer.com/companies/mindtree), [Morgan Stanley](https://scaleengineer.com/companies/morgan-stanley), [Myntra](https://scaleengineer.com/companies/myntra), [Nagarro](https://scaleengineer.com/companies/nagarro), [Nielsen](https://scaleengineer.com/companies/nielsen), [Nutanix](https://scaleengineer.com/companies/nutanix), [Nvidia](https://scaleengineer.com/companies/nvidia), [Oracle](https://scaleengineer.com/companies/oracle), [Ozon](https://scaleengineer.com/companies/ozon), [Palo Alto Networks](https://scaleengineer.com/companies/palo-alto-networks), [PayPal](https://scaleengineer.com/companies/paypal), [Paytm](https://scaleengineer.com/companies/paytm), [Publicis Sapient](https://scaleengineer.com/companies/publicis-sapient), [Pwc](https://scaleengineer.com/companies/pwc), [Qualcomm](https://scaleengineer.com/companies/qualcomm), [Roblox](https://scaleengineer.com/companies/roblox), [SAP](https://scaleengineer.com/companies/sap), [Samsung](https://scaleengineer.com/companies/samsung), [ServiceNow](https://scaleengineer.com/companies/servicenow), [Shopee](https://scaleengineer.com/companies/shopee), [Siemens](https://scaleengineer.com/companies/siemens), [Slice](https://scaleengineer.com/companies/slice), [Snowflake](https://scaleengineer.com/companies/snowflake), [SoFi](https://scaleengineer.com/companies/sofi), [Spotify](https://scaleengineer.com/companies/spotify), [Tech Mahindra](https://scaleengineer.com/companies/tech-mahindra), [Tekion](https://scaleengineer.com/companies/tekion), [TikTok](https://scaleengineer.com/companies/tiktok), [Tinkoff](https://scaleengineer.com/companies/tinkoff), [UKG](https://scaleengineer.com/companies/ukg), [Uber](https://scaleengineer.com/companies/uber), [VMware](https://scaleengineer.com/companies/vmware), [Visa](https://scaleengineer.com/companies/visa), [Walmart Labs](https://scaleengineer.com/companies/walmart-labs), [Western Digital](https://scaleengineer.com/companies/western-digital), [Wipro](https://scaleengineer.com/companies/wipro), [Wise](https://scaleengineer.com/companies/wise), [Wissen Technology](https://scaleengineer.com/companies/wissen-technology), [Wix](https://scaleengineer.com/companies/wix), [Yahoo](https://scaleengineer.com/companies/yahoo), [Yandex](https://scaleengineer.com/companies/yandex), [Yelp](https://scaleengineer.com/companies/yelp), [ZScaler](https://scaleengineer.com/companies/zscaler), [Zoho](https://scaleengineer.com/companies/zoho), [athenahealth](https://scaleengineer.com/companies/athenahealth), [eBay](https://scaleengineer.com/companies/ebay), [jio](https://scaleengineer.com/companies/jio), [persistent systems](https://scaleengineer.com/companies/persistent-systems), [tcs](https://scaleengineer.com/companies/tcs)
---
## Problem
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.

You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.

You can return the answer in any order.

**Example 1:**

**Input:** nums = [2,7,11,15], target = 9
**Output:** [0,1]
**Explanation:** Because nums[0] + nums[1] == 9, we return [0, 1].

**Example 2:**

**Input:** nums = [3,2,4], target = 6
**Output:** [1,2]

**Example 3:**

**Input:** nums = [3,3], target = 6
**Output:** [0,1]

**Constraints:**

* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**

**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?

# Approaches
## Brute Force
The most straightforward approach is to check every possible pair of numbers in the array. We can use two nested loops to iterate through all pairs and see if their sum equals the target.
**Time:** O(n²) · **Space:** O(1)
**Pros:** Simple to understand and implement.; Uses constant extra space.
**Cons:** Inefficient for large input arrays due to its quadratic time complexity.
### Explanation
We use two nested loops to find the pair of numbers. The outer loop, with index `i`, iterates from the beginning of the array to the end. The inner loop, with index `j`, starts from `i + 1` to avoid using the same element twice and to avoid duplicate pairs. Inside the inner loop, we check if `nums[i] + nums[j]` is equal to the `target`. If the sum is equal to the target, we have found our solution and can return the indices `[i, j]`. Since the problem guarantees exactly one solution, we don't need to worry about finding multiple pairs or no pairs at all.

```java
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{}; // Should not be reached as per problem statement
    }
}
```
### Algorithm
- Iterate through the array with an index `i` from 0 to `n-2`.
- For each `i`, iterate through the rest of the array with an index `j` from `i+1` to `n-1`.
- Check if `nums[i] + nums[j] == target`.
- If the condition is true, return `[i, j]`.

## Two-Pass Hash Table
To improve the time complexity, we can use a hash table (or HashMap in Java). A hash table allows us to check for the existence of an element in constant time on average. This approach involves two separate passes over the array.
**Time:** O(n) · **Space:** O(n)
**Pros:** Significantly faster than the brute-force approach with linear time complexity.
**Cons:** Requires extra space proportional to the number of elements in the array.; Requires two passes over the input array.
### Explanation
In the first pass, we iterate through the array and populate a hash map. The keys of the map are the numbers from the array, and the values are their corresponding indices. In the second pass, we iterate through the array again. For each element `nums[i]`, we calculate its required complement: `complement = target - nums[i]`. We then check if this `complement` exists as a key in our hash map. An important edge case is that the complement found in the map must not be `nums[i]` itself. We verify this by checking if the index stored for the complement (`map.get(complement)`) is different from the current index `i`. If the complement exists and its index is different, we have found the solution and return `[i, map.get(complement)]`.

```java
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        // First pass: build the hash map
        for (int i = 0; i < nums.length; i++) {
            numMap.put(nums[i], i);
        }
        // Second pass: find the complement
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement) && numMap.get(complement) != i) {
                return new int[]{i, numMap.get(complement)};
            }
        }
        return new int[]{}; // Should not be reached
    }
}
```
### Algorithm
- Create a hash map to store elements and their indices.
- Iterate through the array and populate the hash map with `(number, index)` pairs.
- Iterate through the array a second time.
- For each element `nums[i]`, calculate `complement = target - nums[i]`.
- Check if `complement` exists in the hash map and its index is not `i`.
- If both conditions are met, return `[i, map.get(complement)]`.

## One-Pass Hash Table
We can optimize the two-pass hash table approach into a single pass. While iterating and inserting elements into the hash table, we can also look back to check if the current element's complement already exists in the table. This combines the building and checking phases into one.
**Time:** O(n) · **Space:** O(n)
**Pros:** Most optimal solution with linear time complexity.; Slightly more efficient than the two-pass approach as it combines two loops into one.
**Cons:** Requires extra space proportional to the number of elements in the array.
### Explanation
We create an empty hash map and iterate through the `nums` array just once. For each element `nums[i]`, we first calculate the `complement = target - nums[i]`. Then, we check if this `complement` is already a key in our hash map. If it is, we have found our pair. The complement must have been inserted at an earlier iteration, so we can immediately return its index from the map along with the current index `i`: `[map.get(complement), i]`. If the complement is not in the map, we insert the current number `nums[i]` and its index `i` into the map. This is done so that subsequent elements can find it if it's their complement. This approach works because by the time we find a complement in the map, we are guaranteed to have two different indices, as we check for the complement *before* adding the current element to the map.

```java
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement)) {
                return new int[]{numMap.get(complement), i};
            }
            numMap.put(nums[i], i);
        }
        return new int[]{}; // Should not be reached
    }
}
```
### Algorithm
- Create an empty hash map.
- Iterate through the array with an index `i` from 0 to `n-1`.
- For each element `nums[i]`, calculate `complement = target - nums[i]`.
- Check if `complement` exists as a key in the hash map.
- If it exists, return `[map.get(complement), i]`.
- If it does not exist, add the current element and its index to the map: `map.put(nums[i], i)`.

# Solutions
### CSharp

```csharp
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        var m = new Dictionary < int,
            int > ();
        for (int i = 0, j;; ++i) {
            int x = nums[i];
            int y = target - x;
            if (m.TryGetValue(y, out j)) {
                return new [] {
                    j,
                    i
                };
            }
            if (!m.ContainsKey(x)) {
                m.Add(x, i);
            }
        }
    }
}
```

### Java

```java
class Solution { public int [] twoSum ( int [] nums , int target ) { Map < Integer , Integer > m = new HashMap <>(); for ( int i = 0 ;; ++ i ) { int x = nums [ i ]; int y = target - x ; if ( m . containsKey ( y )) { return new int [] { m . get ( y ), i }; } m . put ( x , i ); } } }
```

### JavaScript

```javascript
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum =
  function (nums, target) {
    const m = new Map();
    for (let i = 0; ; ++i) {
      const x = nums[i];
      const y = target - x;
      if (m.has(y)) {
        return [m.get(y), i];
      }
      m.set(x, i);
    }
  };

```

### CPP

```cpp
class Solution {
public:
  vector<int> twoSum(vector<int> &nums, int target) {
    unordered_map<int, int> m;
    for (int i = 0;; ++i) {
      int x = nums[i];
      int y = target - x;
      if (m.count(y)) {
        return {m[y], i};
      }
      m[x] = i;
    }
  }
};

```

### Python

```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]: m = {} for i, x in enumerate(nums): y = target - x if y in m: return [m[y], i] m[x] = i

```
