LearnCoding

Distinct pairs with a target sum

Warm-upHash map, Two sum

Problem

Return all distinct value pairs (a, b) with a ≤ b and a + b = target, where a and b come from different positions in nums (so a == b needs at least two occurrences). Sort the result ascending.

Signature

def pairs_with_sum(nums: list[int], target: int) -> list[tuple[int, int]]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> pairs_with_sum([1, 2, 3, 4, 5], 6) == [(1, 5), (2, 4)]
True

>>> pairs_with_sum([3, 3, 3], 6) == [(3, 3)]
True

Solve it in your own editor; nothing on this page runs code.

Hints

Use a Counter or set; for each value, look up the complement.

a == b needs at least two occurrences; deduplicate; return pairs sorted ascending.

Pair an element with a different position, not itself.

Reference solution

from collections import Counter

def pairs_with_sum(nums, target):
    c = Counter(nums); out = set()
    for a in c:
        b = target - a
        if b in c and (a < b or (a == b and c[a] >= 2)):
            out.add((a, b))
    return sorted(out)

What a strong solution covers

  • Counter or set, O(n).
  • Correct handling of a == b.
  • Deduplication.
  • Discusses the sorted two-pointer alternative and memory trade-offs.

Common mistakes

  • pairing an element with itself
  • emitting both (a, b) and (b, a).

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.