3Sum

3Sum is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the Converging (Sorted Array Target Sum) subpattern.

Problem statement

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

Topics and companies

Topics: Array, Two Pointers, Sorting.

Reported in interviews at Amazon, Facebook, Microsoft, Bloomberg, Apple, Adobe, VMware, Google, Cisco, Tesla, Goldman Sachs, eBay.

How to practise 3Sum on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n^2), where n is the length of nums. The outer loop runs O(n) times, and for each i, the two-pointer scan runs in O(n) time (since each pair is only considered once due to the sorted array and pointer movement). time and O(1) (excluding the space for the output). The algorithm sorts the array in-place and uses only a constant amount of extra space for pointers and variables. The output space is O(k), where k is the number of unique triplets found. space.

Open 3Sum in the code editor, or read the 3Sum editorial for a worked solution with its approach and complexity analysis.

Where 3Sum sits in the DSA pattern sheet

Problems related to 3Sum

Other problems that use the same Converging (Sorted Array Target Sum) and Two Pointers techniques:

Preparing this workspace.