---
title: Distinct pairs with a target sum
url: https://gurkanozkan.ai/learn/coding/mle-distinct-pairs-with-a-target-sum-33/
markdown: https://gurkanozkan.ai/learn/coding/mle-distinct-pairs-with-a-target-sum-33.md
kind: coding
difficulty: Warm-up
topics:
  - Hash map
  - Two sum
json: https://gurkanozkan.ai/api/learn/coding/mle-distinct-pairs-with-a-target-sum-33.json
robots: noindex
---

# Distinct pairs with a target sum

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

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

## Examples

Each call and the value it should give.

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

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

## Hints

1. Use a Counter or set; for each value, look up the complement.
2. a == b needs at least two occurrences; deduplicate; return pairs sorted ascending.
3. Pair an element with a different position, not itself.

## Reference solution

```python
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.*
