LeetCode 15: 3Sum — Python Solution

LeetCode 15: 3Sum is a Medium two pointers problem. This Python walkthrough develops a sort plus two pointers solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicTwo Pointers
Reusable patternsort plus two pointers
ComplexityO(n^2) time and O(1) auxiliary space aside from sorting

Recognizing the pattern

Two pointers are useful when one comparison lets you permanently discard one side of the remaining search range.

For this problem specifically, sort the values, fix one number, and use two pointers to find complementary pairs while skipping duplicates. The invariant worth writing beside the code is: For each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique.

Step-by-step algorithm

  1. Identify the input state consumed by threeSum(nums) and initialize the data required by the sort plus two pointers pattern.
  2. Sort the values, fix one number, and use two pointers to find complementary pairs while skipping duplicates.
  3. After each update, verify the page’s central invariant: For each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique.
  4. Finish only after the boundary behavior is covered: Skip duplicate fixed values and duplicate pointer values after every match.

Python solution

class Solution:
    def threeSum(self, nums):
        nums.sort(); answer = []
        for i in range(len(nums) - 2):
            if i and nums[i] == nums[i - 1]: continue
            if nums[i] > 0: break
            left, right = i + 1, len(nums) - 1
            while left < right:
                total = nums[i] + nums[left] + nums[right]
                if total < 0: left += 1
                elif total > 0: right -= 1
                else:
                    answer.append([nums[i], 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
        return answer

Reading the implementation

The main entry point is threeSum(nums). The named working state includes left, total; those variables make the sort plus two pointers state visible instead of hiding it in incidental control flow.

The implementation uses 4 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, sort the values, fix one number, and use two pointers to find complementary pairs while skipping duplicates.

Correctness argument

Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.

Preservation. Sort the values, fix one number, and use two pointers to find complementary pairs while skipping duplicates. The chosen movement discards only candidates that cannot improve the answer; afterward, for each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique.

Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.

Complexity and trade-offs

O(n^2) time and O(1) auxiliary space aside from sorting. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A quadratic pair scan is easier to invent but repeats comparisons that pointer movement can eliminate. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert sorted(Solution().threeSum([-1,0,1,2,-1,-4])) == [[-1,-1,2],[-1,0,1]]

Common mistakes and edge cases

  • Problem-specific boundary: Skip duplicate fixed values and duplicate pointer values after every match.
  • Pattern-level pitfall: Move the pointer justified by the comparison, and state whether the active interval includes or excludes each endpoint.
  • Invariant check: after every update, confirm that for each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique.

Interview review checklist

  • Explain why sort plus two pointers matches the structure of this input.
  • State the invariant in one sentence before tracing code: For each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique.
  • Derive O(n^2) time and O(1) auxiliary space aside from sorting from how many times each element or state is visited.
  • Test the boundary explicitly: Skip duplicate fixed values and duplicate pointer values after every match.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 11. Container With Most Water · Next: 209. Minimum Size Subarray Sum