Solve LeetCode 15: 3Sum in Python with a sort plus two pointers approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Two Pointers |
| Reusable pattern | sort plus two pointers |
| Complexity | O(n^2) time and O(1) auxiliary space aside from sorting |
What the problem is testing
Sort the values, fix one number, and use two pointers to find complementary pairs while skipping duplicates.
Algorithm
- Sort the values, fix one number, and use two pointers to find complementary pairs while skipping duplicates.
- Maintain this invariant: For each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
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 answerWhy this is correct
The proof follows the maintained state: For each fixed value, pointer moves discard sums that cannot reach zero, and emitted triples are unique. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(n^2) time and O(1) auxiliary space aside from sorting. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Skip duplicate fixed values and duplicate pointer values after every match.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 11. Container With Most Water · Next: 209. Minimum Size Subarray Sum