{"id":10600,"date":"2026-11-29T08:50:38","date_gmt":"2026-11-29T08:50:38","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10600"},"modified":"2026-11-29T08:50:38","modified_gmt":"2026-11-29T08:50:38","slug":"3sum-in-python-sorting-and-two-pointers-explained","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10600","title":{"rendered":"3Sum in Python: Sorting and Two Pointers Explained"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Given an integer array, return every unique triplet of values whose sum is zero. Each triplet must use three distinct indices; the order of results does not matter. This medium-level interview problem combines sorting, two pointers and duplicate elimination. Unlike Two Sum, returning only the first match is not enough.<\/p>\n<h2 class=\"wp-block-heading\">Example<\/h2>\n<p class=\"wp-block-paragraph\">[-1,0,1,2,-1,-4] gives [-1,-1,2] and [-1,0,1].<\/p>\n<h2 class=\"wp-block-heading\">Pattern recognition and hints<\/h2>\n<p class=\"wp-block-paragraph\"><strong>Hint 1:<\/strong> Start by enumerating every combination of three indices.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Hint 2:<\/strong> Sort the array so increasing the left pointer increases or preserves the sum.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Hint 3:<\/strong> Fix one value and solve a two-pointer search on its suffix. Skip repeated anchors and repeated pointer values after a match.<\/p>\n<h2 class=\"wp-block-heading\">Brute force<\/h2>\n<p>from itertools import combinations<br \/>\ndef brute(nums):<br \/>\n    return sorted({tuple(sorted(t)) for t in combinations(nums,3)<br \/>\n                   if sum(t)==0})<\/p>\n<p class=\"wp-block-paragraph\">The brute-force version checks every combination of three distinct indices. Sorting each matching triple makes it canonical; a set removes duplicates. It returns tuples, while the optimized implementation returns lists. Normalize the output when comparing them.<\/p>\n<h2 class=\"wp-block-heading\">Optimized or iterative approach<\/h2>\n<p class=\"wp-block-paragraph\">Sort first, fix one element, and search the remaining suffix with two pointers.<\/p>\n<p>def three_sum(nums):<br \/>\n    a = sorted(nums)<br \/>\n    out = []<br \/>\n    for i in range(len(a)-2):<br \/>\n        if i and a[i] == a[i-1]:<br \/>\n            continue<br \/>\n        if a[i] &gt; 0:<br \/>\n            break<br \/>\n        l, r = i+1, len(a)-1<br \/>\n        while l &lt; r:<br \/>\n            total = a[i]+a[l]+a[r]<br \/>\n            if total &lt; 0:<br \/>\n                l += 1<br \/>\n            elif total &gt; 0:<br \/>\n                r -= 1<br \/>\n            else:<br \/>\n                out.append([a[i],a[l],a[r]])<br \/>\n                l += 1<br \/>\n                r -= 1<br \/>\n                while l &lt; r and a[l] == a[l-1]:<br \/>\n                    l += 1<br \/>\n                while l &lt; r and a[r] == a[r+1]:<br \/>\n                    r -= 1<br \/>\n    return out<\/p>\n<h2 class=\"wp-block-heading\">Pseudocode<\/h2>\n<p>SORT a copy of nums<br \/>\nFOR each anchor i through n-3:<br \/>\n  SKIP repeated anchors; STOP if anchor is positive<br \/>\n  SET left = i+1, right = n-1<br \/>\n  WHILE left &lt; right:<br \/>\n    COMPUTE sum of anchor, left, right<br \/>\n    IF sum &lt; 0: move left rightward<br \/>\n    ELSE IF sum &gt; 0: move right leftward<br \/>\n    ELSE: record triplet, move both, skip duplicates<br \/>\nRETURN results<\/p>\n<h2 class=\"wp-block-heading\">Step-by-step walkthrough<\/h2>\n<p class=\"wp-block-paragraph\">Sorted input: -4,-1,-1,0,1,2. Fix -1 at index 1; pointers find -1 and 2, then 0 and 1. Skip the next duplicate fixed value.<\/p>\n<p>AnchorLeftRightSumAction0 (-4)1 (-1)5 (2)-3Move left0 (-4)2 (-1)5 (2)-3Move left0 (-4)3 (0)5 (2)-2Move left0 (-4)4 (1)5 (2)-1Move left; pointers meet1 (-1)2 (-1)5 (2)0Record [-1,-1,2]; move both1 (-1)3 (0)4 (1)0Record [-1,0,1]; move both2 (-1)\u2014\u2014\u2014Skip duplicate anchor3 (0)4 (1)5 (2)3Move right; pointers meet<\/p>\n<h2 class=\"wp-block-heading\">Correctness argument<\/h2>\n<p class=\"wp-block-paragraph\">In a sorted suffix, if the sum is too small, the current left value cannot work with any smaller right value. The symmetric argument applies to an excessive sum. Skipping equal values preserves distinct value triplets.<\/p>\n<p class=\"wp-block-paragraph\">Every unique triplet has a smallest value that can serve as its anchor. Searching the sorted suffix covers all remaining candidates. After a match, repeating either matched value would only reproduce the same value triplet; moving both pointers and skipping equal values therefore loses no unique result.<\/p>\n<h2 class=\"wp-block-heading\">Complexity analysis<\/h2>\n<p class=\"wp-block-paragraph\">Brute force enumerates O(n\u00b3) triples; set operations are expected constant time, and sorting k distinct results adds O(k log k) time. It stores O(k) results. The optimized algorithm sorts in O(n log n) time, then performs at most O(n) pointer movements for each of O(n) anchors: O(n\u00b2) total time. Python\u2019s sorted copy and sorting workspace use O(n) auxiliary space, excluding the O(k) output.<\/p>\n<h2 class=\"wp-block-heading\">Edge cases<\/h2>\n<p class=\"wp-block-paragraph\">Test [] and [1,2] \u2192 []; [0,0,0,0] \u2192 [[0,0,0]]; [1,2,3] \u2192 []; [-3,-2,-1] \u2192 []; [-2,0,0,2,2] \u2192 [[-2,0,2]]. Avoid using the same index twice or returning repeated triplets.<\/p>\n<h2 class=\"wp-block-heading\">Interview follow-ups<\/h2>\n<p class=\"wp-block-paragraph\">Why skip duplicates after a match? They produce the same triplet. Why sort a copy? It preserves the caller\u2019s input.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Can hashing solve 3Sum?<\/strong> Yes, a per-anchor hash set can find pairs in expected O(n\u00b2) time, but deduplication needs care.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Why stop at a positive anchor?<\/strong> All subsequent sorted values are positive, so their sum cannot be zero.<\/p>\n<p class=\"wp-block-paragraph\"><strong>How would you generalize?<\/strong> For 4Sum, fix two values and use two pointers for the remaining pair; handle duplicates at each level.<\/p>\n<h2 class=\"wp-block-heading\">Practice and revision<\/h2>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/leetcode.com\/problems\/3sum\/\" target=\"_blank\" rel=\"noopener\">Original problem<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/dsa-roadmap\/\">DSA Roadmap<\/a><\/p>","protected":false},"excerpt":{"rendered":"<p>Given an integer array, return every unique triplet of values whose sum is zero. Each triplet must use three distinct indices; the order of results does not matter. This medium-level interview problem combines sorting, two pointers and duplicate elimination. Unlike Two Sum, returning only the first match is not enough. Example [-1,0,1,2,-1,-4] gives [-1,-1,2] and [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10601,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10600","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10600"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10600"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10600\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10601"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10600"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10600"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10600"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}