{"id":32000,"date":"2026-12-01T22:04:28","date_gmt":"2026-12-01T22:04:28","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=32000"},"modified":"2026-12-01T22:04:28","modified_gmt":"2026-12-01T22:04:28","slug":"python-example-code-find-all-the-pairs-of-numbers-which-sum-upto-k","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-example-code-find-all-the-pairs-of-numbers-which-sum-upto-k\/","title":{"rendered":"Python Example Code: Find all the pairs of numbers which sum upto `k`"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This page shows how to find every pair of numbers in a Python list that adds up to a target value <code>k<\/code>, 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.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/1c69787e6abba0c8824cf0d38c992c48.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the example above actually prints<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The gist loops over each number and checks whether <code>k - num<\/code> is also in the list. With the input <code>[0, 14, 0, 4, 7, 8, 3, 5, 7]<\/code> and <code>k = 11<\/code>, running it prints:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">$ python3 find_pairs_sum_k.py\n&#91;(4, 7), (7, 4), (8, 3), (3, 8), (7, 4)]<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\">There are really only two distinct pairs, <code>(3, 8)<\/code> and <code>(4, 7)<\/code>. The output has five entries because the code reports each pair from both sides and once more for the second <code>7<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Problems with the original code<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Pairs are repeated and reversed.<\/strong> <code>(4, 7)<\/code> and <code>(7, 4)<\/code> are the same pair, and duplicate values in the input add more copies.<\/li>\n\n\n<li><strong>A number can pair with itself.<\/strong> <code>find_pairs([5, 1], 10)<\/code> returns <code>[(5, 5)]<\/code>, even though the list contains only one <code>5<\/code>. The check <code>(k - num) in num_array<\/code> finds the same element it started from.<\/li>\n\n\n<li><strong>It is O(n\u00b2).<\/strong> <code>in<\/code> on a Python list is a linear scan, so the loop runs about n \u00d7 n comparisons. With large lists this gets slow quickly.<\/li>\n\n\n<li><strong>The wording is ambiguous.<\/strong> &quot;Sum upto <code>k<\/code>&quot; means the pair sums to exactly <code>k<\/code> in this code. A pair whose sum is less than or equal to <code>k<\/code> is a different problem, covered in the FAQ below.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected version: unique pairs with a hash set (O(n))<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>seen<\/code> only after its own check, it can never match itself. A value like <code>5<\/code> pairs with <code>5<\/code> only when it really appears twice.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def find_pairs(nums, k):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Return each distinct pair of values (a, b), a &lt;= b, with a + b == k.\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    seen = set()\n    pairs = set()\n    <span class=\"hljs-keyword\">for<\/span> num in nums:\n        complement = k - num\n        <span class=\"hljs-keyword\">if<\/span> complement in seen:\n            <span class=\"hljs-comment\"># Store in a fixed order so (7, 4) and (4, 7) collapse to one entry<\/span>\n            pairs.add((min(num, complement), max(num, complement)))\n        seen.add(num)\n    <span class=\"hljs-keyword\">return<\/span> sorted(pairs)\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">\"__main__\"<\/span>:\n    <span class=\"hljs-keyword\">print<\/span>(find_pairs(&#91;<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">14<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>, <span class=\"hljs-number\">8<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">7<\/span>], <span class=\"hljs-number\">11<\/span>))  <span class=\"hljs-comment\"># &#91;(3, 8), (4, 7)]<\/span>\n    <span class=\"hljs-keyword\">print<\/span>(find_pairs(&#91;<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">1<\/span>], <span class=\"hljs-number\">10<\/span>))                         <span class=\"hljs-comment\"># &#91;]<\/span>\n    <span class=\"hljs-keyword\">print<\/span>(find_pairs(&#91;<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">5<\/span>], <span class=\"hljs-number\">10<\/span>))                         <span class=\"hljs-comment\"># &#91;(5, 5)]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><code>sorted(pairs)<\/code> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Variant: every pair of positions (indices)<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes the question asks for every combination of positions, so two <code>7<\/code>s at different indices count as separate pairs. Map each value to the list of indices where it has appeared so far:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">from collections import defaultdict\n\n\ndef find_index_pairs(nums, k):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Return every (i, j) with i &lt; j and nums&#91;i] + nums&#91;j] == k.\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    positions = defaultdict(<span class=\"hljs-keyword\">list<\/span>)  <span class=\"hljs-comment\"># value -&gt; indices seen so far<\/span>\n    result = &#91;]\n    <span class=\"hljs-keyword\">for<\/span> j, num in enumerate(nums):\n        <span class=\"hljs-keyword\">for<\/span> i in positions.get(k - num, &#91;]):\n            result.append((i, j))\n        positions&#91;num].append(j)\n    <span class=\"hljs-keyword\">return<\/span> result\n\n\n<span class=\"hljs-keyword\">print<\/span>(find_index_pairs(&#91;<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">14<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>, <span class=\"hljs-number\">8<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">7<\/span>], <span class=\"hljs-number\">11<\/span>))\n<span class=\"hljs-comment\"># &#91;(3, 4), (5, 6), (3, 8)]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The index <code>4<\/code> (value 4) pairs with both <code>7<\/code>s, at indices 4 and 8. Building the map is O(n), but the output can hold up to about n\u00b2\/2 pairs (for example, all zeros with <code>k = 0<\/code>), so the worst case is O(n\u00b2) simply because of how many results there are. If you only need the <strong>count<\/strong>, add <code>len(positions.get(k - num, []))<\/code> to a counter instead of building the list. To keep that O(n), store a count per value instead of a list of indices.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Alternative: two pointers on a sorted list<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def find_pairs_sorted(nums, k):\n    nums = sorted(nums)\n    left, right = <span class=\"hljs-number\">0<\/span>, len(nums) - <span class=\"hljs-number\">1<\/span>\n    pairs = &#91;]\n    <span class=\"hljs-keyword\">while<\/span> left &lt; right:\n        total = nums&#91;left] + nums&#91;right]\n        <span class=\"hljs-keyword\">if<\/span> total == k:\n            pairs.append((nums&#91;left], nums&#91;right]))\n            left += <span class=\"hljs-number\">1<\/span>\n            right -= <span class=\"hljs-number\">1<\/span>\n            <span class=\"hljs-keyword\">while<\/span> left &lt; right <span class=\"hljs-keyword\">and<\/span> nums&#91;left] == nums&#91;left - <span class=\"hljs-number\">1<\/span>]:\n                left += <span class=\"hljs-number\">1<\/span>\n            <span class=\"hljs-keyword\">while<\/span> left &lt; right <span class=\"hljs-keyword\">and<\/span> nums&#91;right] == nums&#91;right + <span class=\"hljs-number\">1<\/span>]:\n                right -= <span class=\"hljs-number\">1<\/span>\n        elif total &lt; k:\n            left += <span class=\"hljs-number\">1<\/span>\n        <span class=\"hljs-keyword\">else<\/span>:\n            right -= <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> pairs\n\n\n<span class=\"hljs-keyword\">print<\/span>(find_pairs_sorted(&#91;<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">14<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>, <span class=\"hljs-number\">8<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">7<\/span>], <span class=\"hljs-number\">11<\/span>))  <span class=\"hljs-comment\"># &#91;(3, 8), (4, 7)]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Sorting costs O(n log n) and the pointer scan costs O(n). Python&#039;s <code>sorted()<\/code> returns a new list. Use <code>nums.sort()<\/code> to sort in place if you are allowed to modify the input.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing an approach<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Approach<\/th><th>Time<\/th><th>Extra space<\/th><th>Returns<\/th><\/tr><\/thead><tbody><tr><td>Original (list <code>in<\/code> check)<\/td><td>O(n\u00b2)<\/td><td>O(p) for the result<\/td><td>Repeated, reversed and self pairs (buggy)<\/td><\/tr><tr><td>Hash set<\/td><td>O(n)<\/td><td>O(n)<\/td><td>Each distinct value pair once<\/td><\/tr><tr><td>Index map<\/td><td>O(n + p)<\/td><td>O(n + p)<\/td><td>Every pair of positions<\/td><\/tr><tr><td>Two pointers<\/td><td>O(n log n)<\/td><td>O(1) beyond the sort<\/td><td>Each distinct value pair once, in sorted order<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Testing the edge cases<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These assertions catch the bugs described above. Save them next to the hash-set <code>find_pairs<\/code> function and run the file with <code>python3<\/code>. If nothing prints, every check passed.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">assert find_pairs(&#91;], <span class=\"hljs-number\">5<\/span>) == &#91;]                       <span class=\"hljs-comment\"># empty input<\/span>\nassert find_pairs(&#91;<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">1<\/span>], <span class=\"hljs-number\">10<\/span>) == &#91;]                  <span class=\"hljs-comment\"># no self-pairing<\/span>\nassert find_pairs(&#91;<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">5<\/span>], <span class=\"hljs-number\">10<\/span>) == &#91;(<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">5<\/span>)]            <span class=\"hljs-comment\"># real duplicate pair<\/span>\nassert find_pairs(&#91;<span class=\"hljs-number\">-2<\/span>, <span class=\"hljs-number\">13<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>], <span class=\"hljs-number\">11<\/span>) == &#91;(<span class=\"hljs-number\">-2<\/span>, <span class=\"hljs-number\">13<\/span>), (<span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>)]  <span class=\"hljs-comment\"># negatives<\/span>\nassert find_pairs(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">1<\/span>], <span class=\"hljs-number\">2<\/span>) == &#91;(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">1<\/span>)]       <span class=\"hljs-comment\"># reported once<\/span>\nassert find_pairs(&#91;<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">14<\/span>, <span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>, <span class=\"hljs-number\">8<\/span>, <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">7<\/span>], <span class=\"hljs-number\">11<\/span>) == &#91;(<span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">8<\/span>), (<span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">7<\/span>)]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Why does the original code return (7, 4) as well as (4, 7)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the time complexity of the two-sum pairs problem in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>in<\/code> check is O(n\u00b2).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I count pairs whose sum is less than or equal to k?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Sort the list and use two pointers. If nums[left] + nums[right] &lt;= k, every element from left+1 up to right pairs with nums[left], so add right &#8211; left to the count and move left forward. Otherwise move right back. This counts index pairs in O(n log n).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does the hash-set solution work with negative numbers and zero?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. The complement k &#8211; num is just another integer, so negatives and zeros are looked up in the set like any other value.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How can I return indices instead of values, like LeetCode Two Sum?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">More Python tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-100-interview-questions-for-python\/\">TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-python-interview-questions-and-answers\/\">Top 50 Python Interview Questions and Answers<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[6904],"class_list":["post-32000","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages","tag-algorithms"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/32000","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=32000"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/32000\/revisions"}],"predecessor-version":[{"id":80498,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/32000\/revisions\/80498"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=32000"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=32000"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=32000"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}