<AI/>
enru
Все статьи

3Sum

LeetCode 15: Find all unique triplets in an array that sum up to zero using a hash set, two pointers, or no sorting at all.

Сложность
Средняя
Опубликовано
Темы
#array#two pointers#hash table
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given an integer array nums. Write a function that finds all unique triplets in the array that sum up to zero. Within a triplet [nums[i], nums[j], nums[k]] the same element can't be used twice, i.e. i != j, i != k, j != k.

Note that the answer must not contain duplicate triplets. The order of the triplets and of the numbers within them doesn't matter.

Constraints

  • The array contains from 3 to 3000 values
  • Values are in the range from -105 to 105

Examples

Input: [-1, 0, 1, 2, -1, -4]

Answer: [[-1, -1, 2], [-1, 0, 1]]

Hash Set approach

This solution requires sorting the array in ascending order first, so that's what we do first.

Next, we can notice that the problem is very similar to its simpler sibling: Two sum. The only difference is that we need to find all triplets, and their sum is always zero. We can reuse the approach from that problem and solve this one with an additional HashSet structure or its equivalents.

Let's look at the input [-1, 0, 1, 2, -1, -4].

After sorting we get [-4, -1, -1, 0, 1, 2].

Now we loop over all elements of the array.

For each i-th element we run a separate loop to find the missing pair of numbers for the triplet. Since we always move from left to right, the second loop can start at i + 1 and run to the end.

The first thing to take care of is that our answer must not contain duplicate triplets. If we look at the example input again, we'll see two identical possible solutions [-1, 0, 1]: the array has two triplets with the values at indices 1, 3, 4 and 2, 3, 4. This is easy to handle, though, since the array is sorted. Equal values are adjacent, so we can just check the first one and skip the rest.

We add a check at the very beginning of the outer loop: if we're not at the first element and the current element equals the previous one, we simply skip it. We also create a Set to keep track of the numbers we've already seen.

Here's what we have so far.

typescript
export const threeSumHashSet = (nums: number[]): number[][] => {
  // Create an array for the results
  const result: number[][] = [];
 
  // Sort the array in ascending order first
  nums.sort();
 
  for (let i = 0; i < nums.length; i++) {
    const firstNum = nums[i];
 
    // Skip the current number if it equals the previous one, since it would produce the same result.
    if (i != 0 && nums[i - 1] == firstNum) {
      continue;
    }
 
    const used = new Set<number>();
 
    for (let j = i + 1; j < nums.length; j++) {
      const secondNum = nums[j];
 
      // Implementation
    }
  }
 
  return result;
};

Now we need to decide what happens inside the inner loop. The work there basically boils down to the Two sum problem. We compute the third number needed to get a sum of zero and check whether we've already seen it in the array. That's exactly what our Set is for.

  • If the third number is in used, we add an array of all three numbers to the result.
  • If the third number is not in used, we just add the second number to it and move on.

There's one more nuance to take care of. While iterating in the inner loop we can also encounter equal values and produce duplicates. So after adding a triplet, we need to keep incrementing j while the value at index j equals the value at index j - 1.

As a result, we get the following solution.

typescript
export const threeSumHashSet = (nums: number[]): number[][] => {
  // Create an array for the results
  const result: number[][] = [];
 
  // Sort the array in ascending order first
  nums.sort();
 
  for (let i = 0; i < nums.length; i++) {
    const firstNum = nums[i];
 
    // Skip the current number if it equals the previous one, since it would produce the same result.
    if (i != 0 && nums[i - 1] == firstNum) {
      continue;
    }
 
    const used = new Set<number>();
 
    for (let j = i + 1; j < nums.length; j++) {
      const secondNum = nums[j];
 
      // Compute the missing third number
      const thirdNum = 0 - firstNum - secondNum;
 
      if (used.has(thirdNum)) {
        result.push([firstNum, secondNum, thirdNum]);
        while (j + 1 < nums.length && nums[j] == nums[j + 1]) {
          j++;
        }
      }
 
      used.add(secondNum);
    }
  }
 
  return result;
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

The complexity is O(n2), since we run a loop inside a loop. Sorting adds O(n * log n). The total is O(n * log n) + O(n2), which is asymptotically equivalent to O(n2).

Space Complexity

O(n), since we add up to n elements to the set.

Two pointers approach

Just like the previous one, this solution requires sorting the array first. So the first step is to sort the array in ascending order.

Now we can apply the two pointers approach, just like in the Two sum II problem. The only difference is that we need to find all triplets, and their sum is always zero.

Let's look at the input [-1, 0, 1, 2, -1, -4].

After sorting we get [-4, -1, -1, 0, 1, 2].

Now we loop over all elements of the array.

For each i-th element we run a separate loop to find the missing pair of numbers for the triplet. Since we always move from left to right, the second loop can start at i + 1 and run to the end.

As in the previous solution, we need to make sure there are no duplicates in the answer, so we check each distinct value only once and skip the repeats.

Here's what we have so far.

typescript
export const threeSumTwoPointers = (nums: number[]): number[][] => {
  const result: number[][] = [];
 
  nums.sort();
 
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
 
    if (i != 0 && nums[i - 1] == num) {
      continue;
    }
 
    // Implementation
  }
 
  return result;
};

Now we can take the solution from the Two sum II problem and modify it a little.

  1. Create two pointers that store indices. Set left to i + 1 and right to the index of the last element.
  2. Run a loop that stops when left becomes greater than or equal to right, i.e. when the pointers meet.
  3. On each iteration compute the sum of the elements at left, right and i and compare it with zero:
    • If the sum is greater than zero, we've added numbers that are too large and need smaller ones. We can decrease the sum by taking the number to the left of the one at right. Decrement right by 1.
    • If the sum is less than zero, we've added numbers that are too small and need larger ones. We can increase the sum by taking the number to the right of the one at left. Increment left by 1.
    • If the sum equals zero, we've found the numbers. Add the triplet [nums[i], nums[left], nums[right]] to the answer. Right away, decrement right and increment left by one to look for the next possible combination.

As in the previous solution, there's one nuance left. During the inner iteration we can encounter equal values and produce duplicates. So after adding a triplet, we need to keep incrementing left while the value at index left equals the value at index left - 1.

typescript
export const threeSumTwoPointers = (nums: number[]): number[][] => {
  // Create an array for the results
  const result: number[][] = [];
 
  // Sort the array in ascending order first
  nums.sort();
 
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
 
    // Skip the current number if it equals the previous one, since it would produce the same result.
    if (i != 0 && nums[i - 1] == num) {
      continue;
    }
 
    let left = i + 1;
    let right = nums.length - 1;
 
    while (left < right) {
      const sum = num + nums[left] + nums[right];
 
      if (sum == 0) {
        result.push([num, nums[left], nums[right]]);
        right--;
        left++;
 
        while (left < right && nums[left] == nums[left - 1]) {
          left++;
        }
      } else if (sum > 0) {
        right--;
      } else {
        left++;
      }
    }
  }
 
  return result;
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

The complexity is O(n2), since we run a loop inside a loop. Sorting adds O(n * log n). The total is O(n * log n) + O(n2), which is asymptotically equivalent to O(n2).

Space Complexity

Varies from O(log n) to O(n) depending on the sorting algorithm implementation. The pointers take constant memory O(1), so the final space complexity is determined by the sorting algorithm.

No-sort approach

This approach doesn't require sorting the input array. We can slightly modify the Hash Set solution from above.

Again, we iterate over all elements of the array and on each iteration run a separate loop starting from i + 1. To avoid checking repeated numbers, we record each one in a Hash Set dups and check at the start of each iteration whether the element is already there. If it is, we just skip the iteration.

We also define a Hash Map seen, where we record the numbers we've already checked as the second number of a pair, along with the first number firstNum they were seen with. With this, on each iteration of the inner loop we can compute the missing number thirdNum and check whether it's already in seen. If it is, we've found a triplet.

Now we need to avoid adding identical triplets to the answer. There's a neat trick for this, but it doesn't work in every language.

In languages like Python and Java, we can create an array (list) of three elements, sort it and add it to another Hash Set uniq. Adding sorted triplets automatically gets rid of duplicates thanks to how a Hash Set works. At the end, we just convert the Hash Set into an array and return it.

However, in languages like Go, JavaScript and TypeScript this won't work. In Go, slices can't be used as keys because they are not comparable. In JavaScript and TypeScript, arrays can be used, but they are compared by reference, so identical arrays can be added to a Set multiple times, since their references differ.

In these languages we have to use a string key like 1.2.3, where the three numbers of the triplet are written in sorted order, separated by dots. This creates a unique key and prevents duplicates. However, when returning the result, we have to parse each string back into individual numbers.

typescript
export const threeSumNoSort = (nums: number[]): number[][] => {
  const uniq = new Set<string>();
  const dups = new Set<number>();
  const seen = new Map<number, number>();
 
  for (let i = 0; i < nums.length; i++) {
    const firstNum = nums[i];
 
    if (dups.has(firstNum)) {
      continue;
    }
 
    dups.add(firstNum);
 
    for (let j = i + 1; j < nums.length; j++) {
      const secondNum = nums[j];
 
      // Compute the missing third number
      const thirdNum = 0 - firstNum - secondNum;
 
      if (seen.has(thirdNum) && seen.get(thirdNum) === firstNum) {
        // Build the triplet
        const triplet = [firstNum, secondNum, thirdNum];
 
        // Sort the triplet to avoid duplicates
        triplet.sort();
 
        // Convert the triplet to a string and add it to the set
        uniq.add(triplet.join('.'));
      }
 
      seen.set(secondNum, firstNum);
    }
  }
 
  // Convert the set of strings back into an array
  return Array.from(uniq).reduce<number[][]>((acc, tripletStr) => {
    const tripletArr = tripletStr.split('.');
    const triplet = tripletArr.map((numStr) => Number(numStr));
    return [...acc, triplet];
  }, []);
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

The complexity is O(n2), since we run a loop inside a loop.

Although the asymptotic complexity is the same as in the previous solutions, this algorithm is noticeably slower in practice. Hash set lookups, while constant time, are expensive compared to direct memory access.

Space Complexity

O(n), since we create additional structures whose size depends on the input array length.