Start learning free

LESSON 349 OF 673 · TWO POINTERS

3Sum in Python: O(n²) with Sorting and Two Pointers

Practice O(n2) Read the full explanation

You get a list of integers nums.

Return every triplet of numbers that adds up to 0. The three numbers must come from three different positions.

List each triplet of values once. Two triplets with the same three values count as one, even if they come from different positions.

Write each triplet from its smallest value to its largest. Then list the triplets from smallest to largest. Compare their first values, then their second, then their third.

If you sort nums first and collect the triplets from left to right, they come out in this order.

 

Example 1:

Input: nums = [3,-2,-1,1,-2,4]
Output: [[-2,-2,4],[-2,-1,3]]
Explanation:
(-2) + (-2) + 4 = 0 uses both -2s (positions 1 and 4).
(-2) + (-1) + 3 = 0 works with either -2. It is listed once.
Both triplets start with -2.
Their second values are -2 and -1.
Since -2 is smaller, the triplet with both -2s comes first.

Example 2:

Input: nums = [5,-1,2,7]
Output: []
Explanation: No three of these numbers add up to 0.

Example 3:

Input: nums = [1,-1,0,1,-1,0]
Output: [[-1,0,1]]
Explanation: Many choices of positions give (-1) + 0 + 1 = 0.
They all use the same values, so the triplet appears once.
[0,0,0] would need three zeros. There are only two.

 

Constraints:

  • 3 to 3,000 numbers.
  • Each number is from -100,000 to 100,000.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space, apart from sorting and the triplets it returns.

STEP 1 OF 15
    Ctrl + Enter to check

    PYTHON · TWO POINTERS

    3sum in Python, explained

    Problem overview

    The method threeSum receives a list of integers, nums, and returns every triplet [nums[i], nums[j], nums[k]] where i, j and k are three different indices and the three values add up to 0. The answer must not contain duplicates: triplets made of the same three values count once, whichever indices they come from. Each triplet is written in ascending order, and the triplets are listed in ascending order too, comparing first values, then second, then third.

    For nums = [-1, 0, 1, 2, -1, -4] the answer is [[-1, -1, 2], [-1, 0, 1]]. For [0, 0, 0, 0] it is [[0, 0, 0]]: several index choices give 0 + 0 + 0, but they all form the same triplet. The lesson asks for O(n²) time and no extra space beyond sorting and the output.

    Approach: sort, fix one number, squeeze the other two

    Trying every triple of indices is O(n³), and with up to 3000 numbers that is far too slow. Removing duplicates from the result afterwards would need extra bookkeeping as well.

    Sorting the list first makes both problems easy. For each choice of the first number nums[i], the other two must be found among the elements to its right, and they must sum to -nums[i]. That is the two-pointer technique on a sorted list: put left just after i and right at the end, and look at the total:

    • If the total is below 0, it is too small. The only way to raise it is to move left right, to a bigger value.
    • If the total is above 0, it is too big, and moving right left gives a smaller value.
    • If the total is 0, the triplet is recorded and both pointers move inward.

    Each pointer only moves one way, so the scan for one value of i takes O(n) steps, and over all values of i the work is O(n²).

    Sorting also puts equal values side by side, so repeats are easy to skip. The sorted list is scanned from left to right, with i < left < right, so every triplet comes out already in ascending order, and the triplets themselves come out in ascending order.

    On [-1, 0, 1, 2, -1, -4], the sorted list is [-4, -1, -1, 0, 1, 2]. With i at the first -1, the pointers find -1 + -1 + 2 and then -1 + 0 + 1. The second -1 is skipped as a first number, because it would repeat the same search.

    Step by step

    1. Sort nums with its sort() method.
    2. Store the length in n.
    3. Create an empty result. Because the list is sorted and scanned left to right, triplets are appended in the required order.
    4. Fix the first number with i in range(n - 2). The other two numbers sit to its right, so i stops two places before the end.
    5. Skip a repeated first number: if i > 0 and nums[i] == nums[i - 1], continue. The same first value would find the same triplets again.
    6. Set the pointers: left is i + 1 and right is n - 1.
    7. Loop while left < right. When they meet, every pair for this i has been checked.
    8. Compute total as nums[i] + nums[left] + nums[right].
    9. Total below 0: move left right.
    10. Total above 0: move right left.
    11. Total equal to 0: append [nums[i], nums[left], nums[right]] to result.
    12. Move both pointers inward. Keeping one in place would need the other's old value again, and that gives the same triplet.
    13. Skip repeated second numbers: while left < right and nums[left] == nums[left - 1], move left right.
    14. Return result.

    The loop for right is not needed. After left moves to a new value, an old value at right would make the total too big, and the "above 0" branch moves right by itself.

    The solution in Python

    class Solution:
        def threeSum(self, nums: List[int]) -> List[List[int]]:
            nums.sort()
            n = len(nums)
            result = []
            for i in range(n - 2):
                if i > 0 and nums[i] == nums[i - 1]:
                    continue
                left, right = i + 1, n - 1
                while left < right:
                    total = nums[i] + nums[left] + nums[right]
                    if total < 0:
                        left += 1
                    elif total > 0:
                        right -= 1
                    else:
                        result.append([nums[i], nums[left], nums[right]])
                        left += 1
                        right -= 1
                        while left < right and nums[left] == nums[left - 1]:
                            left += 1
            return result
    

    The Python details that matter here:

    • nums.sort() sorts in place and returns None. It changes the caller's list, which is allowed here. sorted(nums) would return a new list and leave the original alone, at the cost of O(n) extra space.
    • range(n - 2) is empty for fewer than three elements, so a short list returns [] without special handling.
    • continue skips the rest of the loop body and goes on with the next i.
    • The triplet is a new list each time. The expression [nums[i], nums[left], nums[right]] copies the three values, so later pointer moves do not change what was stored.
    • Variable name total. Avoid calling it sum, which would hide Python's built-in function.

    Complexity

    Time: O(n²). Sorting costs O(n log n). After that, each value of i runs a two-pointer scan in which left and right together move at most n steps, so the loops cost O(n²). That outweighs the sort.

    Space: O(1) extra, apart from the sort and the returned triplets. The method keeps a few integers.

    Edge cases and common mistakes

    • Many equal values. [0, 0, 0, 0] gives one triplet, [[0, 0, 0]]. The first zero is used as i, and the other zeros are skipped as first numbers.
    • Exactly three elements. [0, 0, 0] gives [[0, 0, 0]], and [1, 2, -3] gives [[-3, 1, 2]], because the sort puts the values in ascending order.
    • No answer. [0, 1, 1] gives [].
    • A repeated value inside a triplet is fine. [-2, 0, 1, 1, 2] gives [[-2, 0, 2], [-2, 1, 1]]. The repeated 1 is used twice, because those are two different indices. Only repeats at the same position in a triplet are skipped.
    • Skipping with the wrong neighbour. Comparing nums[i] with nums[i + 1] would skip the first copy and lose triplets like [-1, -1, 2]. Comparing with the previous element keeps the first copy.
    • Not moving the pointers after a match leaves the loop running on the same triplet forever. Both must move.

    Testing

    • [-1, 0, 1, 2, -1, -4] gives [[-1, -1, 2], [-1, 0, 1]].
    • [0, 1, 1] gives [].
    • [0, 0, 0, 0] gives [[0, 0, 0]].
    • [-2, 0, 1, 1, 2] gives [[-2, 0, 2], [-2, 1, 1]].
    • [1, 2, -3] gives [[-3, 1, 2]].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free