Two Sum

EasyHashing · Complement Lookup🧩 Hashing & CountingLeetCode #1 ↗Updated

Problem

You are given an integer array nums and a number target. Find two different positions whose values add up to target and return their indices (in any order). Exactly one valid pair is guaranteed, and the same element may not be used twice.
Inputnums = [2,7,11,15], target = 9Output[0,1]
Inputnums = [3,2,4], target = 6Output[1,2]
Inputnums = [3,3], target = 6Output[0,1]

2 ≤ n ≤ 104  ·  -109 ≤ nums[i], target ≤ 109  ·  exactly one answer  ·  Follow-up: beat O(n2).

Try it yourself

Java
class Solution {
    public int[] twoSum(int[] nums, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
For each value x the partner is fixed: target - x. Remember every value you have already passed in a hash map (value → index), and each lookup for the partner becomes O(1).
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceTry Every Pair

Time O(n2)Space O(1)

Fix the first index i, then scan every later index j and test nums[i] + nums[j] == target. Starting j at i + 1 guarantees two different positions and checks each pair once.

Java
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[0]; // unreachable: a pair is guaranteed
}

No extra memory, but about n2/2 pair checks — too slow for the follow-up.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every PairO(n2)O(1)
BetterSort Indices + Two PointersO(n log n)O(n)
OptimalOne-Pass Hash MapO(n)O(n)
Common pitfalls
  • Inserting before looking up — [3,2,4], 6 wrongly pairs index 0 with itself.
  • Sorting the values directly — the original indices are lost.
  • Pre-filling the map in a separate pass without checking j != i.
Interview tips
  • Ask: indices or values? Sorted input? Duplicates? Always exactly one answer?
  • Mention the sorted two-pointer variant (LC 167) uses O(1) extra space.
  • Say the phrase complement lookup — it generalises to many sum problems.
Pattern
Hash map of seen values → when each element's partner is fully determined (e.g. target - x) and you need it fast.
My notes saved in this browser