Skip to main content

Given a list of integers and a target, return every unique pair of values that adds up to the target. For example, for 2, 7, 4, 5, 7, 2 and target 9, return the pairs 2 and 7, and 4 and 5.

Coding rounds · Intermediate 1

Short answer

Walk the list once with a set of values already seen. For each x, check if target - x is in the set; if so, record the pair in sorted form in a result set. Then add x to the seen set. This is O(n) time and O(n) memory, against O(n squared) for two nested loops.

Deeper answer

First clarify the output. Ask whether to return values or index positions, whether the same pair should appear once when the list has repeated numbers, and whether one element can be used twice. Ask if the list is sorted and how long it is.

For unique value pairs, keep seen = set() and found = set(). For each x, compute the complement target - x. If the complement is in seen, add (min(x, target - x), max(x, target - x)) to found, so 2 and 7 is stored once whichever comes first. After the check, run seen.add(x). Checking before adding means a single 5 does not pair with itself for target 10, but two 5s do.

Set lookups are O(1) on average, so the pass is O(n) time and O(n) memory. If the list is already sorted and memory is tight, two pointers from both ends give O(1) extra memory. Test an empty list, no valid pair, negative numbers, and 5, 5, 5 with target 10, which must return one pair.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Lists and dictionaries

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.