Skip to content

Two Sum

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input has exactly one solution, and you may not use the same element twice. You can return the answer in any order.

InputTargetOutputExplanation
[2, 7, 11, 15]9[0, 1]nums[0] + nums[1] = 2 + 7 = 9
[3, 2, 4]6[1, 2]nums[1] + nums[2] = 2 + 4 = 6
[3, 3]6[0, 1]nums[0] + nums[1] = 3 + 3 = 6
  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Exactly one valid answer exists.
ApproachTimeSpaceReturnsBest When
Brute ForceO(n²)O(1)IndicesArray is tiny, no extra memory allowed
Hash MapO(n)O(n)IndicesGeneral case — fast lookup, unsorted input
Two-PointerO(n log n)O(n)*ValuesArray is already sorted or indices not required

* A sorted copy of the array is made to preserve the original order.

  • Pick Hash Map if you want the best all-around interview answer.
  • Pick Brute Force if you are still learning how to reason about pairs.
  • Pick Two-Pointer only if you are practicing the pattern or if the data is already sorted.
Best For Speed
Hash Map
O(n) time · O(n) space
Sorted Input
Two-Pointer
O(n log n) time · O(n) space
No Extra Memory
Brute Force
O(n²) time · O(1) space
★ Recommended

For each number, compute its complement (target - num) and check if that complement was already seen. Store each number → index mapping as we iterate.

The key idea is simple: instead of searching the whole array again, remember each number as you go. When the matching partner appears later, you can answer immediately.

⏱ Time O(n) Single pass 💾 Space O(n) Hash map storage

Input: nums = [2, 7, 11, 15], target = 9

Stepinumcomplementseen (before)Action
1027{}7 not in seen → store {2: 0}
2172{2: 0}2 found at index 0 → return [0, 1]

Animated walkthrough

How the hash map solution finds the answer

Use Next or Autoplay to watch the current index, the complement calculation, and the lookup table change after each step.

Step 1 of 3 Target: 9
Waiting to begin...
Array state
Memory / lookup state

function twoSumHashMap(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
two_sum_hash_map.py
from typing import List
def two_sum_hash_map(nums: List[int], target: int) -> List[int]:
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
print(two_sum_hash_map([2, 7, 11, 15], target=9)) # [0, 1]
🎯 Interview Favourite

Sort the numbers, place one pointer at the beginning and one at the end, then adjust them based on whether the current sum is too small or too large.

⏱ Time O(n log n) Sort-dominated 💾 Space O(n) Sorted copy

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

After sorting: [2, 3, 4]

Stepleftrightsorted[left]sorted[right]SumAction
102246== target → return [2, 4]

Input: nums = [2, 7, 11, 15], target = 9

After sorting: [2, 7, 11, 15]

Stepleftrightsorted[left]sorted[right]SumAction
10321517> target → right—
20221113> target → right—
301279== target → return [2, 7]
function twoSumTwoPointer(nums, target):
sorted = sort(copy of nums)
left, right = 0, len(sorted) - 1
while left < right:
currentSum = sorted[left] + sorted[right]
if currentSum == target:
return [sorted[left], sorted[right]]
elif currentSum < target:
left++
else:
right--
return []
two_sum_two_pointer.py
from typing import List
def two_sum_two_pointer(nums: List[int], target: int) -> List[int]:
nums_sorted = sorted(nums)
left, right = 0, len(nums_sorted) - 1
while left < right:
current_sum = nums_sorted[left] + nums_sorted[right]
if current_sum == target:
return [nums_sorted[left], nums_sorted[right]]
elif current_sum < target:
left += 1
else:
right -= 1
return []
print(two_sum_two_pointer([2, 7, 11, 15], target=9)) # [2, 7]
print(two_sum_two_pointer([3, 2, 4], target=6)) # [2, 4]
print(two_sum_two_pointer([3, 3], target=6)) # [3, 3]
✓ Simple

Check every possible pair using two nested loops.

This is the most direct approach. It is slow for large inputs, but it is a good mental starting point because there is almost no trick to it.

⏱ Time O(n²) All pairs checked 💾 Space O(1) No extra memory

Input: nums = [2, 7, 11, 15], target = 9

ijnums[i]nums[j]SumMatch?
01279✓ → return [0, 1]

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

ijnums[i]nums[j]SumMatch?
01325
02347
12246✓ → return [1, 2]
function twoSumBruteForce(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
two_sum_brute_force.py
"""
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]
"""
# Approach 1: Brute Force
# This approach involves using two nested loops to iterate through every possible pair of numbers in the array and checking if their sum equals the target.
# Time Complexity: O(n^2)
from typing import List
def two_sum_brute_force(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
print(two_sum_brute_force([2,7,11,15], target = 9)) # [0, 1]