Two Sum
The drill: Find the two positions in an array whose values add up to a target — each position used once. The full, official statement lives on LeetCode; this page is the training plan.
An array of integers and a target value arrive together. Somewhere in that array sit exactly two positions whose values add up to the target — the drill is to find them and hand back their indexes.
A position can only be used once: an index never pairs with itself, though two different positions holding the same value are fair game. Every input on this course is built so exactly one valid pair exists.
The answer is the two indexes, in either order. The interesting question is not whether you can find the pair — a double loop always can — but what it costs, and what one pass with a little memory buys you.
- at least two elements — a pair is always possible
- values and the target can be negative, zero, or positive
- exactly one valid pair per input on this course
- the two indexes may come back in any order
HINT 1 THE NUDGE
Brute force checks every pair — n² work, because each element keeps re-scanning the whole array. What single question does each element actually need answered?
HINT 2 THE STRUCTURE
For a value v, the only thing that matters is: have I already walked past target − v? “Have I seen it” is a membership question — and there’s a structure that answers membership in O(1).
HINT 3 ONE STEP FROM THE ANSWER
One pass with a value→index map. For each element, look up its complement before inserting itself. Miss → remember me and move on. Hit → the answer is the stored index and this one.
Target 18. The map starts empty — it will remember every value we walk past.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {} # value -> index
for i, v in enumerate(nums):
need = target - v
if need in seen:
return [seen[need], i]
seen[v] = i
return []class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n): # anchor each position...
for j in range(i + 1, n): # ...re-scan everything after it
if nums[i] + nums[j] == target:
return [i, j]
return []class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (seen.containsKey(need)) {
return new int[] { seen.get(need), i };
}
seen.put(nums[i], i);
}
return new int[] {};
}
}class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED