We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

3Sum

Number: 15

Difficulty: Medium

Paid? No

Companies: Google, Meta, Amazon, Bloomberg, Microsoft, Visa, TikTok, Cloudflare, Adobe, Walmart Labs, Oracle, Agoda, Turing, Vimeo, Apple, tcs, Goldman Sachs, Yahoo, PayPal, Barclays, Morgan Stanley, Myntra, Accenture, HCL, BNY Mellon, Intuit, Uber, Docusign, Altimetrik, Yandex, ServiceNow, Nutanix, Cisco, Zoho, DoorDash, Tesla, Sprinklr, Rakuten, ASUS, Dream11, Bosch, Nvidia, Works Applications, Wix


Problem Description

Given an integer array, find all unique triplets in the array that sum up to 0. Each triplet should consist of three distinct indices, and the solution set must not contain duplicate triplets.


Key Insights

  • Sort the array to efficiently skip duplicates and facilitate the two pointers approach.
  • Use a fixed pointer for the first element, and then use two additional pointers (left and right) to find pairs that sum to the negation of the fixed element.
  • Skip duplicate elements to ensure unique triplets.

Space and Time Complexity

Time Complexity: O(n²) where n is the number of elements in the array.
Space Complexity: O(1) extra space (ignoring the space required for the output).


Solution

We first sort the array to bring duplicates together and allow the two-pointer technique to work efficiently. Then, iterate over the array and for each element, use two pointers (one at the beginning right after the current element and one at the end of the array) to find a pair that sums with the current element to zero. Skip duplicates for the current element and within the inner loop to avoid duplicate triplets. This ensures that each valid triplet is unique and the overall runtime remains efficient.


Code Solutions

# Function to find all unique triplets that sum to zero.
def threeSum(nums):
    # Sort the array to facilitate finding duplicates and using two pointers.
    nums.sort()
    result = []
    n = len(nums)

    # Iterate through the array, fixing one element at a time.
    for i in range(n - 2):
        # Skip duplicate elements for the first element.
        if i > 0 and nums[i] == nums[i - 1]:
            continue
            
        left, right = i + 1, n - 1
        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]
            # Check if the triplet adds up to zero.
            if current_sum == 0:
                result.append([nums[i], nums[left], nums[right]])
                # Skip duplicates for the second element.
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                # Skip duplicates for the third element.
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1
                left += 1
                right -= 1
            elif current_sum < 0:
                left += 1
            else:
                right -= 1

    return result

# Example usage:
#print(threeSum([-1,0,1,2,-1,-4]))
← Back to All Questions