# 9. 15. 3Sum

15\. 3SumMedium26.7K2.4KCompanies

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:**

<pre><code><strong>Input: nums = [-1,0,1,2,-1,-4]
</strong><strong>Output: [[-1,-1,2],[-1,0,1]]
</strong><strong>Explanation: 
</strong>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.
</code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [0,1,1]
</strong><strong>Output: []
</strong><strong>Explanation: The only possible triplet does not sum up to 0.
</strong></code></pre>

**Example 3:**

<pre><code><strong>Input: nums = [0,0,0]
</strong><strong>Output: [[0,0,0]]
</strong><strong>Explanation: The only possible triplet sums up to 0.
</strong></code></pre>

**Constraints:**

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

{% embed url="<https://leetcode.com/problems/3sum/description/>" %}

#### better

> no conversion from arr to string, string to arr

> 98% BEAT

```jsx
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    nums.sort((a, b) => a - b);
    let answer = [];

    let prev = undefined;
    for (let i = 0; i < nums.length; i++) {
        if (prev === nums[i]) continue;
        prev = nums[i];

        let left = i + 1;
        let right = nums.length - 1;

        while (left < right) {
            const sum = nums[left] + nums[i] + nums[right];
            if (sum === 0) {
                const arr = [nums[left], nums[i], nums[right]];
                answer.push(arr);
                left++;
                right--;
                
                while (left < right && nums[left - 1] === nums[left]) {
                    left++;
                }
                
                while (left < right && nums[right] === nums[right + 1]) {
                    right--;
                }

            } else if (sum < 0) {
                left++;
            } else {
                right--;
            }
        }
    }

    return answer;
};
```

### ok

```jsx
var threeSum = function(nums) {
    nums.sort((a, b) => a - b);
    let answer = new Set();

    for (let i = 1; i < nums.length - 1; i++) {
        let left = 0;
        let m = i;
        let right = nums.length - 1;

        while (left < m && m < right) {
            const sum = nums[left] + nums[i] + nums[right];
            if (sum === 0) {
                answer.add([nums[left], nums[i], nums[right]].join());
                left++;
                right--;

								// 10% faster
                while (left < right && nums[left - 1] === nums[left]) {
                    left++;
                }
                
                while (left < right && nums[right] === nums[right + 1]) {
                    right--;
                }

            } else if (sum < 0) {
                left++;
            } else {
                right--;
            }
        }
    }

    return [...answer].map(s => s.split(','));
};
```

### good, but can be better?

> time: O(n^2)

> space: O(n)

```jsx
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    
    const answer = new Set();
    for (let i = 1; i < nums.length - 1; i++) {
        const arr = {};
        for (let prev = 0; prev < i; prev++) {
            const diff = nums[i] + nums[prev];
            if (arr[-diff] === undefined) {
                arr[-diff] = new Set();
            }

            arr[-diff].add(nums[prev]);
        }

        for (let next = i + 1; next < nums.length; next++) {
            if (arr[nums[next]] === undefined) continue;
            for (const prev of arr[nums[next]]) {
                const arr = [prev, nums[i], nums[next]];
                arr.sort();
                answer.add(arr.join());
            }
        }
    }

    return [...answer].map(s => s.split(','));
};
```
