3Sum Visualizer & Step-by-Step Algorithm Solution

Find all unique triplets that sum to zero with sorting and two pointers.

Category: arrays | Difficulty: Medium

Tags: Two Pointers, Sorting, Duplicate Handling

3Sum

Array (nums)
-1
0
0
1
1
2
2
3
-1
4
-4
5
100%
state
nums.length6
triplets found0
Initialization
1/35
Explanation

Start threeSum algorithm.

Source Code
1function threeSum(nums) {
2 if (!nums.length) return [];
3 nums.sort((a, b) => a - b);
4 const result = [];
5 const n = nums.length;
6 for (let i = 0; i < n - 2; i++) {
7 if (i > 0 && nums[i] === nums[i - 1]) continue;
8 let j = i + 1, k = n - 1;
9 while (j < k) {
10 const sum = nums[i] + nums[j] + nums[k];
11 if (sum === 0) {
12 result.push([nums[i], nums[j], nums[k]]);
13 j++; k--;
14 while (j < k && nums[j] === nums[j - 1]) j++;
15 while (j < k && nums[k] === nums[k + 1]) k--;
16 } else if (sum < 0) {
17 j++;
18 } else {
19 k--;
20 }
21 }
22 }
23 return result;
24}