Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
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]
You are given:
numstargetYou must find two different indices i and j such that:
nums[i] + nums[j] == targetImportant details:
Example:
nums = [2, 7, 11, 15]target = 9We need two numbers that sum to 9.
9 - 2 = 7[0, 1]That âpartnerâ number has a name:
complement = target - current_value
This word âcomplementâ is the key that unlocks the hash table solution.
A beginner will naturally try:
i, try every j > inums[i] + nums[j] == targetThis always works, but it can be slow.
Pseudo:
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²)$
If n = 10,000, then pairs â 50 million. Thatâs too big.
So we ask:
Can we avoid checking all pairs?
Instead of searching pairs explicitly, we can do:
When I look at a number x, I know exactly what I need:
target - xSo the whole problem becomes:
For each element
x, check quickly whether its complement has appeared earlier.
The phrase âcheck quicklyâ suggests a data structure:
So:
value -> indexLetâs say we are scanning the array from left to right.
At index i, we see value x = nums[i].
We want to know if there exists some earlier index j such that:
nums[j] + nums[i] = target
Rearrange:
nums[j] = target - nums[i]
So the earlier value we need is:
complement = target - x
If we have a dictionary of all earlier numbers, we can check:
complement already in the dictionary?
j (the stored index), and current i gives the pair.x with its index and continue.This guarantees we never use the same element twice.
Because when weâre at index i, the dictionary only contains indices < i.
So j is always different from i.
When youâre at position i, you ask:
âHave I already seen the number that would complete my target?â
Thatâs the entire algorithm.
Example:
nums = [2, 7, 11, 15]target = 9Initialize:
seen = {} (empty dictionary)seen? â Noseen[2] = 0seen = {2: 0}seen? â
Yesseen[2] = 0[0, 1]Done.
Example:
nums = [3, 3]target = 6Correct answer is [0, 1].
Trace:
Works perfectly.
Example:
nums = [-1, -2, -3, -4, -5]target = -8Pick -3 + -5 = -8 Hash map handles negatives naturally.
This is basically the duplicate case:
If you do:
seen[x] = iYou might accidentally match the same element when target = 2*x.
Example:
nums = [3], target=6â Fix: check first, then store.
People think:
But sorting changes indices, and you must return original indices. You can still do it, but it becomes more complex (need to keep original indices). Hash map is the intended clean solution.
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# seen maps: number -> index where we first saw it
seen = {}
for i, x in enumerate(nums):
complement = target - x
# If complement already seen, we found the pair
if complement in seen:
return [seen[complement], i]
# Otherwise remember x for future elements
seen[x] = i
# LeetCode guarantees exactly one solution, so we usually never reach here.
return []
seen = {}
Create an empty dictionary that will remember numbers we have encountered.for i, x in enumerate(nums):
Go through the list, where:
i is the indexx is the value at that indexcomplement = target - x
Compute the number needed to pair with x to reach target.if complement in seen:
Check if we have already encountered the needed partner number.return [seen[complement], i]
If yes, return:
iseen[x] = i
If complement doesnât exist yet, store current number and its index,
so future elements can pair with it.We use extra memory (dictionary) to avoid the expensive nested loop.
If the interviewer asks âExplain your reasoningâ:
x, we need target - x.âThat is basically the perfect explanation.
Once you understand this, you can recognize many cousin problems:
The pattern is:
Transform a âpair conditionâ into a âlookup conditionâ.
target - x