This page shows how to find every pair of numbers in a Python list that adds up to a target value k, a common coding-interview question. The example above gives a short starting version. Below you will find its exact output, the bugs it contains, and three corrected solutions: a hash-set version, an index-pair version and a two-pointer version, with their time complexity.
What the example above actually prints
The gist loops over each number and checks whether k - num is also in the list. With the input [0, 14, 0, 4, 7, 8, 3, 5, 7] and k = 11, running it prints:
$ python3 find_pairs_sum_k.py
[(4, 7), (7, 4), (8, 3), (3, 8), (7, 4)]
There are really only two distinct pairs, (3, 8) and (4, 7). The output has five entries because the code reports each pair from both sides and once more for the second 7.
Problems with the original code
- Pairs are repeated and reversed.
(4, 7)and(7, 4)are the same pair, and duplicate values in the input add more copies. - A number can pair with itself.
find_pairs([5, 1], 10)returns[(5, 5)], even though the list contains only one5. The check(k - num) in num_arrayfinds the same element it started from. - It is O(nยฒ).
inon a Python list is a linear scan, so the loop runs about n ร n comparisons. With large lists this gets slow quickly. - The wording is ambiguous. "Sum upto
k" means the pair sums to exactlykin this code. A pair whose sum is less than or equal tokis a different problem, covered in the FAQ below.
Corrected version: unique pairs with a hash set (O(n))
Most interviewers want each distinct pair of values reported once. Keep a set of numbers already seen. For each new number, look up its complement in that set. Set lookups take constant time on average, so the whole function is O(n). Because a number is added to seen only after its own check, it can never match itself. A value like 5 pairs with 5 only when it really appears twice.
def find_pairs(nums, k):
"""Return each distinct pair of values (a, b), a <= b, with a + b == k."""
seen = set()
pairs = set()
for num in nums:
complement = k - num
if complement in seen:
# Store in a fixed order so (7, 4) and (4, 7) collapse to one entry
pairs.add((min(num, complement), max(num, complement)))
seen.add(num)
return sorted(pairs)
if __name__ == "__main__":
print(find_pairs([0, 14, 0, 4, 7, 8, 3, 5, 7], 11)) # [(3, 8), (4, 7)]
print(find_pairs([5, 1], 10)) # []
print(find_pairs([5, 5], 10)) # [(5, 5)]Code language: PHP (php)
sorted(pairs) is only there to make the output predictable. If order does not matter, return the set directly. That keeps the function at O(n) and avoids the O(p log p) sort, where p is the number of pairs found.
Variant: every pair of positions (indices)
Sometimes the question asks for every combination of positions, so two 7s at different indices count as separate pairs. Map each value to the list of indices where it has appeared so far:
from collections import defaultdict
def find_index_pairs(nums, k):
"""Return every (i, j) with i < j and nums[i] + nums[j] == k."""
positions = defaultdict(list) # value -> indices seen so far
result = []
for j, num in enumerate(nums):
for i in positions.get(k - num, []):
result.append((i, j))
positions[num].append(j)
return result
print(find_index_pairs([0, 14, 0, 4, 7, 8, 3, 5, 7], 11))
# [(3, 4), (5, 6), (3, 8)]Code language: PHP (php)
The index 4 (value 4) pairs with both 7s, at indices 4 and 8. Building the map is O(n), but the output can hold up to about nยฒ/2 pairs (for example, all zeros with k = 0), so the worst case is O(nยฒ) simply because of how many results there are. If you only need the count, add len(positions.get(k - num, [])) to a counter instead of building the list. To keep that O(n), store a count per value instead of a list of indices.
Alternative: two pointers on a sorted list
If extra memory is a concern, or the input is already sorted, sort the list and move two pointers inward. When the sum is too small, move the left pointer right. When it is too large, move the right pointer left. After a match, skip over duplicate values so each pair is reported once.
def find_pairs_sorted(nums, k):
nums = sorted(nums)
left, right = 0, len(nums) - 1
pairs = []
while left < right:
total = nums[left] + nums[right]
if total == k:
pairs.append((nums[left], nums[right]))
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < k:
left += 1
else:
right -= 1
return pairs
print(find_pairs_sorted([0, 14, 0, 4, 7, 8, 3, 5, 7], 11)) # [(3, 8), (4, 7)]Code language: PHP (php)
Sorting costs O(n log n) and the pointer scan costs O(n). Python's sorted() returns a new list. Use nums.sort() to sort in place if you are allowed to modify the input.
Choosing an approach
| Approach | Time | Extra space | Returns |
|---|---|---|---|
Original (list in check) | O(nยฒ) | O(p) for the result | Repeated, reversed and self pairs (buggy) |
| Hash set | O(n) | O(n) | Each distinct value pair once |
| Index map | O(n + p) | O(n + p) | Every pair of positions |
| Two pointers | O(n log n) | O(1) beyond the sort | Each distinct value pair once, in sorted order |
Note: In the table, p is the number of pairs returned. In interviews, start with the hash-set solution, then mention the two-pointer option as a lower-memory alternative.
Testing the edge cases
These assertions catch the bugs described above. Save them next to the hash-set find_pairs function and run the file with python3. If nothing prints, every check passed.
assert find_pairs([], 5) == [] # empty input
assert find_pairs([5, 1], 10) == [] # no self-pairing
assert find_pairs([5, 5], 10) == [(5, 5)] # real duplicate pair
assert find_pairs([-2, 13, 4, 7], 11) == [(-2, 13), (4, 7)] # negatives
assert find_pairs([1, 1, 1, 1], 2) == [(1, 1)] # reported once
assert find_pairs([0, 14, 0, 4, 7, 8, 3, 5, 7], 11) == [(3, 8), (4, 7)]Code language: PHP (php)
Frequently asked questions
Why does the original code return (7, 4) as well as (4, 7)?
It checks every element on its own, so when it reaches 4 it finds 7, and when it reaches 7 it finds 4. Storing each pair as (min, max) in a set removes these mirrored duplicates.
What is the time complexity of the two-sum pairs problem in Python?
The hash-set solution runs in O(n) average time with O(n) extra space. The sorted two-pointer solution runs in O(n log n) time with constant extra space beyond the sort. A nested loop or a list in check is O(nยฒ).
How do I count pairs whose sum is less than or equal to k?
Sort the list and use two pointers. If nums[left] + nums[right] <= k, every element from left+1 up to right pairs with nums[left], so add right – left to the count and move left forward. Otherwise move right back. This counts index pairs in O(n log n).
Does the hash-set solution work with negative numbers and zero?
Yes. The complement k – num is just another integer, so negatives and zeros are looked up in the set like any other value.
How can I return indices instead of values, like LeetCode Two Sum?
Use a dictionary that maps each value to its index (or to a list of indices). When the complement is already in the dictionary, return its stored index together with the current index.
Related tutorials
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- Top 50 Python Interview Questions and Answers
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals