← Back to Algorithms, page 1

algorithms-0003 · Easy fresher

Two Sum: given a list of integers and a target, return the indices of two numbers that add up to the target.

For each number x, the partner you need is target - x. Walk through the list once, and before storing x in a dictionary of value to index, check whether target - x is already there. This gives O(n) time and O(n) space instead of checking all pairs in O(n^2). If the list is sorted, two pointers solve it in O(1) extra space.

Full answer

Problem

Given nums and target, return a pair of indices (i, j) with i < j and nums[i] + nums[j] == target, or None if no pair exists.

Example: nums = [2, 7, 11, 15], target = 9 gives (0, 1) because 2 + 7 = 9.

Constraints: 0 <= len(nums) <= 10^4; values and target can be negative; you may not use the same element twice, but equal values at different indices are allowed ([3, 3], target 6 gives (0, 1)).

Brute force

Try every pair: two nested loops, O(n^2) time, O(1) extra space. Fine for 100 items, too slow for 10^5.

Optimal approach

Keep a dictionary index_of from value to the index where it was seen. For each position j with value x:

  1. Compute need = target - x.
  2. If need is in index_of, return (index_of[need], j).
  3. Otherwise store index_of[x] = j.

Why it works

If a valid pair (i, j) exists with i < j, then when the loop reaches j, the value nums[i] was stored earlier, so the lookup finds it. Checking before storing ensures an element is never paired with itself.

Sorted variant

If nums is sorted, put one pointer at each end. If the sum is too small, move the left pointer right (to a bigger value); if too big, move the right pointer left. Each step discards one value that cannot be in any answer. O(n) time, O(1) space. Sorting an unsorted list first costs O(n log n) and loses the original indices unless you sort (value, index) pairs.

Complexity

Hash map: O(n) average time, O(n) space. Two pointers on sorted input: O(n) time, O(1) space.

Code

python
def two_sum(nums, target):
    """Return indices (i, j), i < j, with nums[i] + nums[j] == target, or None."""
    index_of = {}                      # value -> index where we saw it
    for j, x in enumerate(nums):
        need = target - x
        if need in index_of:
            return (index_of[need], j)
        index_of[x] = j
    return None


def two_sum_sorted(nums, target):
    """Same question when nums is sorted: two pointers, O(1) extra space."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return (lo, hi)
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None


if __name__ == "__main__":
    assert two_sum([2, 7, 11, 15], 9) == (0, 1)
    assert two_sum([3, 2, 4], 6) == (1, 2)
    assert two_sum([3, 3], 6) == (0, 1)          # duplicates
    assert two_sum([-1, -2, -3, -4], -6) == (1, 3)
    assert two_sum([1, 2], 7) is None
    assert two_sum([], 0) is None
    assert two_sum_sorted([1, 3, 4, 6, 9], 10) == (0, 4)   # 1 + 9; first pair found from the outside in
    assert two_sum_sorted([1, 2], 5) is None
    print("all tests passed")

Save as a03_two_sum.py and run python3 a03_two_sum.py. It prints all tests passed (Python 3.13.5).

Edge cases

No solution (return None, or follow the problem's convention). Empty list. Duplicates ([3, 3]). Negative numbers. Several valid pairs: the hash version returns the pair whose second index comes first.

Pattern

Complement lookup with a hash map: "have I already seen the value that completes this one?" It reappears in subarray sum equals k, pairs with a given difference, and 4Sum.

python
def two_sum(nums, target):
    """Return indices (i, j), i < j, with nums[i] + nums[j] == target, or None."""
    index_of = {}                      # value -> index where we saw it
    for j, x in enumerate(nums):
        need = target - x
        if need in index_of:
            return (index_of[need], j)
        index_of[x] = j
    return None


def two_sum_sorted(nums, target):
    """Same question when nums is sorted: two pointers, O(1) extra space."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return (lo, hi)
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None


if __name__ == "__main__":
    assert two_sum([2, 7, 11, 15], 9) == (0, 1)
    assert two_sum([3, 2, 4], 6) == (1, 2)
    assert two_sum([3, 3], 6) == (0, 1)          # duplicates
    assert two_sum([-1, -2, -3, -4], -6) == (1, 3)
    assert two_sum([1, 2], 7) is None
    assert two_sum([], 0) is None
    assert two_sum_sorted([1, 3, 4, 6, 9], 10) == (0, 4)   # 1 + 9; first pair found from the outside in
    assert two_sum_sorted([1, 2], 5) is None
    print("all tests passed")

Includes the hash-map solution for any input and the two-pointer solution for sorted input.

Complexity

Time: O(n) average (hash map); O(n) for two pointers on sorted input. Space: O(n) (hash map); O(1) (two pointers). Sorting unsorted input first would add O(n log n) and requires keeping original indices.

By level

Fresher: Writes the nested-loop solution, then the dictionary solution with correct check-then-store order. Tests with duplicates and a no-answer case. Should state the O(n) time and O(n) space cost of the hash map.

Mid: Explains correctness, gives the sorted two-pointer variant with its space advantage and discusses index preservation when sorting. Explains why checking before inserting avoids pairing an element with itself.

Senior: Extends to all unique pairs, k-sum generalisations, streaming input and memory limits, and discusses hash collision behaviour for adversarial data. Discusses the sorted two-pointer variant and when returning indices makes it harder.

Key points

  • Look up target - x before storing x
  • One pass with a dictionary gives O(n) time
  • Checking before storing prevents using one element twice
  • Sorted input allows two pointers with O(1) space
  • Clarify what to return when there is no pair

Common mistakes

  • Storing x before checking and pairing an element with itself
  • Sorting and returning indices from the sorted order
  • Returning values when indices were asked for
  • Assuming exactly one answer without asking

Follow-ups

  • How would you return all pairs without duplicates?
  • What changes if the input is a stream you cannot store?
  • How do you solve 3Sum using this idea?

Tips

  • State the brute force and its cost before optimising
  • Say "complement" and explain the lookup
  • Ask whether the input is sorted

Evaluation rubric

  • Correct O(n) hash solution
  • Handles duplicates and no-solution cases
  • Explains why the check-then-store order matters
  • Knows the two-pointer variant