Taro Logo

3Sum

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+38
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
3.1K views
Topics:
ArraysTwo Pointers

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

Constraints:

  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if no such triplets exist that sum to zero, and does the order of the triplets in the output list matter?
  2. Can the input array contain duplicate values, and should the uniqueness constraint apply strictly to the triplet values themselves?
  3. What are the minimum and maximum lengths of the input array `nums`, and can we expect the array to be empty or have fewer than 3 elements?
  4. Are the numbers in the array guaranteed to be standard 32-bit signed integers, and could potential intermediate sum operations lead to integer overflow?
  5. Should the triplets themselves be returned in any specific sorted order (e.g., ascending order of the elements within each triplet)?

Brute Force Solution

Approach

Imagine you are given a collection of numbers and need to find every unique group of three numbers that add up to zero. The brute force approach is the most straightforward way to solve this by testing every single possible combination of three numbers to see which ones work.

Here's how the algorithm would work step-by-step:

  1. Begin by picking the first number from the collection.
  2. Next, pair it with a second number from somewhere else in the collection.
  3. Then, look at every other remaining number to act as the third partner.
  4. Add your chosen group of three numbers together and check if the total comes out to zero.
  5. If the sum is indeed zero, write down this winning trio while making sure you have not already recorded the exact same group of numbers previously.
  6. Repeat this process by shifting your starting choices so you test every possible trio of numbers in the entire collection.
  7. Continue until every single combination has been checked and you are left with your complete list of successful trios.

Code Implementation

def three_sum(number_collection):
    successful_trios = set()
    
    # We test every possible combination of three numbers by iterating through all index triplets
    for first_index in range(len(number_collection)):
        for second_index in range(first_index + 1, len(number_collection)):
            for third_index in range(second_index + 1, len(number_collection)):
                
                current_sum = number_collection[first_index] + number_collection[second_index] + number_collection[third_index]
                
                # We check if the sum equals zero to satisfy the core requirement of the problem
                if current_sum == 0:
                    current_trio = tuple(sorted([number_collection[first_index], number_collection[second_index], number_collection[third_index]]))
                    successful_trios.add(current_trio)
                    
    # Converting the set of tuples back into a list of lists ensures the expected output format
    return [list(trio) for trio in successful_trios]

Big(O) Analysis

Time Complexity
O(n³) – For an input collection of size n, the brute force approach uses three nested loops to test every possible combination of three numbers. The outer loop selects the first number n times, the second nested loop picks a second number for every remaining position, and the innermost loop checks the final number. This drives the cost by repeatedly testing trios, resulting in approximately n cubed over 6 operations, which simplifies to O(n³).
Space Complexity
O(N) – The brute force approach requires extra memory to store the winning trios as they are found and to track unique groups to avoid duplicates. In the worst-case scenario, the number of valid triplets can grow quadratically with the input size N, requiring auxiliary storage proportional to the number of combinations. Additionally, variables used in the nested loops require constant O(1) space. Therefore, the total auxiliary space complexity is dominated by the storage of the output results, simplifying to Big O of N where N is the number of elements in the collection.

Optimal Solution

Approach

Instead of testing every possible combination of three items, the optimal approach organizes everything in order first. This clever arrangement allows us to sweep through systematically and find matching groups with much less effort.

Here's how the algorithm would work step-by-step:

  1. First, line up all the given items in order from smallest to largest.
  2. Pick one starting item from the ordered line, knowing you need to find two more items that will combine with it to reach the target sum.
  3. Place a seeker at the item immediately following your starting choice, and place another seeker at the very end of the line.
  4. Add the starting item and the values of both seekers together to see what the total sum is.
  5. If the total sum is exactly what you are aiming for, save this unique group of three.
  6. If the total sum is too small, move the first seeker inward to increase the total.
  7. If the total sum is too large, move the second seeker inward to decrease the total.
  8. Continue moving the seekers until they meet in the middle, exploring all possibilities for that specific starting item.
  9. Shift your starting item to the next distinct value in line and repeat the whole discovery process, making sure to skip duplicates so you never repeat the same group.
  10. By keeping everything ordered and letting the seekers guide your search, you find every valid combination quickly without blindly guessing every possibility.

Code Implementation

class Solution:
    def threeSum(self, nums: list[int]) -> list[list[int]]:
        collected_triplets = []
        nums.sort()

        # Sorting allows us to use two pointers and efficiently skip duplicate values.
        for index in range(len(nums)):
            if index > 0 and nums[index] == nums[index - 1]:
                continue

            left_seeker = index + 1
            right_seeker = len(nums) - 1

            while left_seeker < right_seeker:
                current_sum = nums[index] + nums[left_seeker] + nums[right_seeker]

                if current_sum == 0:
                    collected_triplets.append([nums[index], nums[left_seeker], nums[right_seeker]])
                    left_seeker += 1
                    right_seeker -= 1

                    # Skipping duplicates here prevents adding identical triplets to our result.
                    while left_seeker < right_seeker and nums[left_seeker] == nums[left_seeker - 1]:
                        left_seeker += 1

                    while left_seeker < right_seeker and nums[right_seeker] == nums[right_seeker + 1]:
                        right_seeker -= 1

                elif current_sum < 0:
                    left_seeker += 1
                else:
                    right_seeker -= 1

        # Returning all unique triplets found that sum up to zero.
        return collected_triplets

Big(O) Analysis

Time Complexity
O(n²) – First, sorting the array of n elements takes O(n log n) time. Then, we use a single loop to pick each starting item, which runs n times. Inside this loop, two seekers traverse the remaining elements in linear time relative to n. Combining the outer loop with the inner seeker traversal gives approximately n * n operations, which simplifies to the dominant O(n²) time complexity.
Space Complexity
O(1) – Beyond the memory required to store the output results, the auxiliary space is driven primarily by the sorting step and a few constant pointer variables. Depending on the sorting algorithm used, the extra memory consumed by the sorting process ranges from O(log N) to O(N), where N is the total number of elements in the input array. Aside from this sorting overhead, only a few primitive variables are used to track indices and sums, resulting in a minimal and constant extra space footprint. Therefore, when excluding the output list, the auxiliary space complexity simplifies to Big O of 1 if sorting in-place.

Edge Cases

Array with fewer than three elements
How to Handle:
Return an empty list immediately since it is impossible to form a triplet.
Array containing all zeros
How to Handle:
The sorting and two-pointer approach correctly finds the single unique triplet [0, 0, 0] and skips subsequent duplicates.
All negative or all positive numbers
How to Handle:
The pointer logic will naturally fail to find any sums equal to zero and return an empty list.
Input with many duplicate values
How to Handle:
Skipping adjacent duplicate elements after processing prevents the generation of duplicate triplets in the result set.
No valid triplets exist that sum to zero
How to Handle:
The algorithm safely completes execution and returns an empty list.
Multiple overlapping valid triplets
How to Handle:
Moving both left and right pointers inward while skipping duplicates ensures all unique combinations are captured.
Maximum sized inputs up to thousands of elements
How to Handle:
Sorting the array first allows an O(N^2) two-pointer scan which easily scales within time limits compared to an O(N^3) brute force.
Extreme boundary values near integer limits
How to Handle:
Standard integer addition is safe here because typical array constraints prevent overflow during the summation of three standard integers.
0/75 completed