3Sum in Python

The 3Sum problem asks us to find all unique triplets in an array that sum to zero. Given an array of integers, we need to identify three elements a, b, c such that a + b + c = 0. For example, in array [-1,0,1,2,-1,-4], the triplets [[-1,-1,2], [-1,0,1]] satisfy this condition.

Algorithm Approach

We use the two-pointer technique with these steps ?

  • Sort the array to enable two-pointer approach
  • Fix one element and use two pointers for the remaining two elements
  • Skip duplicates to ensure unique triplets
  • Move pointers based on the sum comparison

Implementation

def threeSum(nums):
    nums.sort()
    result = []
    
    for i in range(len(nums) - 2):
        # Skip duplicates for the first element
        if i > 0 and nums[i] == nums[i - 1]:
            continue
            
        left = i + 1
        right = len(nums) - 1
        
        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]
            
            if current_sum < 0:
                left += 1
            elif current_sum > 0:
                right -= 1
            else:
                # Found a triplet
                result.append([nums[i], nums[left], nums[right]])
                
                # Skip duplicates for left pointer
                while left < len(nums) - 1 and nums[left] == nums[left + 1]:
                    left += 1
                    
                # Skip duplicates for right pointer
                while right > 0 and nums[right] == nums[right - 1]:
                    right -= 1
                    
                left += 1
                right -= 1
                
    return result

# Test the function
numbers = [-1, 0, 1, 2, -1, -4]
print("Input:", numbers)
print("Output:", threeSum(numbers))
Input: [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]

How It Works

The algorithm works by ?

  1. Sorting: [-4, -1, -1, 0, 1, 2]
  2. Fixing first element: For nums[0] = -4, use two pointers at positions 1 and 5
  3. Two-pointer search: Adjust pointers based on sum comparison
  4. Duplicate handling: Skip identical consecutive elements to avoid duplicate triplets

Time and Space Complexity

Aspect Complexity Explanation
Time O(n²) Outer loop O(n), inner two-pointer O(n)
Space O(1) Only using constant extra space

Example with Different Input

# Test with edge cases
test_cases = [
    [0, 0, 0],           # All zeros
    [1, 2, -2, -1],      # Multiple valid triplets
    [1, 1, 1]            # No valid triplets
]

for nums in test_cases:
    print(f"Input: {nums}")
    print(f"Output: {threeSum(nums)}")
    print()
Input: [0, 0, 0]
Output: [[0, 0, 0]]

Input: [1, 2, -2, -1]
Output: [[-2, 1, 1], [-1, -1, 2]]

Input: [1, 1, 1]
Output: []

Conclusion

The 3Sum problem is efficiently solved using the two-pointer technique after sorting. The key insight is fixing one element and finding pairs that complement it to sum zero, while carefully handling duplicates to ensure unique results.

Updated on: 2026-03-25T07:43:43+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements