Two Sum
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 = 9Output
[0,1]Explanation
Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2
Input
nums = [3,2,4], target = 6Output
[1,2]
Example 3
Input
nums = [3,3], target = 6Output
[0,1]
Constraints
2 <= nums.length <= 10⁴-10⁹ <= nums[i] <= 10⁹-10⁹ <= target <= 10⁹- Only one valid answer exists.
Two Sum
Overview
The goal is to find two distinct indices in an array such that the values at those indices sum to a specific target. Since the problem guarantees exactly one solution and prohibits using the same element twice, we are looking for a unique pair $(a, b)$ such that $a + b = \text{target}$.
The core intuition relies on the relationship: complement = target - current_value. If we know the value we are looking for (the complement), we just need an efficient way to check if it exists elsewhere in the array.
Brute Force
The most straightforward approach is to check every possible pair of numbers in the array. We use two nested loops: the outer loop picks the first element, and the inner loop iterates through the remaining elements to see if their sum equals the target.
def two_sum(nums: list[int], target: int) -> list[int]:
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
- Time complexity: O(n²) — We use nested loops to compare every possible pair, resulting in quadratic time.
- Space complexity: O(1) — We only use a constant amount of extra space for loop variables.
Optimal / Best Approach
We can improve the time complexity significantly by using a Hash Map (Python dictionary). As we iterate through the array, we calculate the complement needed to reach the target. Instead of searching the rest of the array for this complement, we look it up in our dictionary.
- Create an empty dictionary
prev_mapto storevalue: index. - Iterate through
numsusing both indexiand valuen. - Calculate
diff = target - n. - If
diffexists inprev_map, we found our pair. Return[prev_map[diff], i]. - If not, add the current value and its index to
prev_mapand continue.
def two_sum(nums: list[int], target: int) -> list[int]:
# Map to store value -> index
prev_map = {}
for i, n in enumerate(nums):
diff = target - n
if diff in prev_map:
return [prev_map[diff], i]
prev_map[n] = i
- Time complexity: O(n) — We traverse the list containing $n$ elements exactly once. Each lookup in the hash map takes $O(1)$ on average.
- Space complexity: O(n) — In the worst case, we may need to store all $n$ elements in the hash map before finding the complement.
Why This Works
By using a hash map, we trade space for speed.
In the brute force approach, "searching" for the complement takes $O(n)$ time. By storing visited elements in a hash map, "searching" for the complement becomes an $O(1)$ operation. Note that we populate the map as we go; this naturally prevents us from using the same element twice (the current element isn't in the map yet when we check for its complement).
Comments on the solution
No comments on the solution yet. Start a thread about the editorial or your own approach.
- qwerty
// Return Type = list[int] // Type of "nums" = list[int] // Type of "target" = int const two_sum = (nums, target) => { console.log('fsdasadf'); }; - Anonymous
If the array were sorted, two pointers would also work, but the hash map solution does not require sorting.
- Smurfing
Nice classic hash map problem — remember you cannot use the same index twice.
No submissions recorded for this problem yet. Use Submit in the editor — each judge run is stored here.
Output
Input
Expected
Your output
Run to see your output.