Блог пользователя Jayanth25

Автор Jayanth25, история, 4 недели назад, По-английски

Understanding the 3Sum Problem

The 3Sum problem is a classic problem in Data Structures and Algorithms. It helps us understand how sorting and the Two Pointers technique can optimize a brute-force solution.

Let’s understand how to approach this problem step by step.

  1. Problem Statement

Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] such that:

  • i != j
  • i != k
  • j != k
  • nums[i] + nums[j] + nums[k] == 0

The answer should not contain duplicate triplets.

Example

Input:

nums = [-1, 0, 1, 2, -1, -4]

Output:

[[-1, -1, 2], [-1, 0, 1]]

Explanation:

The two unique triplets whose sum is zero are:

  • (-1) + (-1) + 2 = 0
  • (-1) + 0 + 1 = 0
  1. Approach 1: Brute Force

The simplest approach is to generate every possible combination of three elements using three nested loops.

For every combination, check whether its sum is zero.

If it is zero, store the triplet.

To avoid duplicates, we can sort each triplet and use a set.

C++ Code

vector<vector> threeSum(vector& a) { int n = a.size(); set<vector> s; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { for(int k = j + 1; k < n; k++) { if(a[i] + a[j] + a[k] == 0) { vector v = {a[i], a[j], a[k]}; sort(v.begin(), v.end()); s.insert(v); } } } } return vector<vector>(s.begin(), s.end()); }

Complexity Analysis

  • Time Complexity: O(N³ log M), where M is the number of unique triplets, due to set insertion and sorting.
  • Space Complexity: O(M) for storing unique triplets.

This approach works, but it becomes too slow when the array size increases.

Can we optimize it?

  1. Approach 2: Sorting + Two Pointers

This is where the Two Pointers technique comes into play.

Intuition

Instead of checking every possible combination, we can sort the array first.

After sorting, we fix one element and use two pointers to find the remaining two elements.

Let:

  • i represent the first element.
  • j represent the second element.
  • k represent the third element.

Initially:

  • j = i + 1
  • k = n — 1

Now calculate:

sum = a[i] + a[j] + a[k]

There are three possibilities:

Case 1: sum == 0

We found a valid triplet.

Store the triplet and move both pointers.

Case 2: sum < 0

The sum is too small.

Since the array is sorted, increase j to get a larger value.

Case 3: sum > 0

The sum is too large.

Decrease k to get a smaller value.

Continue until the two pointers meet.

C++ Code

vector<vector> threeSum(vector& a) { int n = a.size(); vector<vector> ans; sort(a.begin(), a.end()); for(int i = 0; i < n; i++) { if(i > 0 && a[i] == a[i — 1]) continue; int j = i + 1; int k = n — 1; while(j < k) { int sum = a[i] + a[j] + a[k]; if(sum < 0) { j++; } else if(sum > 0) { k--; } else { ans.push_back({a[i], a[j], a[k]}); j++; k--; while(j < k && a[j] == a[j — 1]) j++; while(j < k && a[k] == a[k + 1]) k--; } } } return ans; }

  1. Dry Run

Consider:

a = [-1, 0, 1, 2, -1, -4]

After sorting:

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

First, fix i = 0.

a[i] = -4 j = 1 k = 5

Sum:

-4 + (-1) + 2 = -3

Since the sum is negative, increment j.

Continue checking until the pointers meet. No valid triplet is found with -4.

Now fix i = 1.

a[i] = -1 j = 2 k = 5

Sum:

-1 + (-1) + 2 = 0

We found our first triplet:

[-1, -1, 2]

Move both pointers.

Now:

j = 3 k = 4

Sum:

-1 + 0 + 1 = 0

We found our second triplet:

[-1, 0, 1]

The pointers now meet, so we stop.

Final Answer:

[[-1, -1, 2], [-1, 0, 1]]

  1. Complexity Analysis

Let N be the size of the array.

  • Sorting: O(N log N)
  • Outer loop: O(N)
  • Two-pointer traversal: O(N) for each fixed element.

Therefore:

Time Complexity: O(N²)

Auxiliary Space Complexity: O(1), excluding the sorting implementation and output storage.

  1. Important Things to Remember

  2. Sorting makes the Two Pointers technique possible.

  3. Fix one element and search for the remaining two.
  4. If the sum is smaller than the target, move the left pointer forward.
  5. If the sum is greater than the target, move the right pointer backward.
  6. Always handle duplicates to avoid repeated triplets.

Conclusion

The most important lesson from this problem is that we don’t always need to check every possible combination.

By sorting the array and using the Two Pointers technique, we reduce the time complexity from cubic to quadratic.

This pattern is also useful in several related problems, such as 4Sum, Two Sum II and other pair or triplet sum problems.

Keep practising and keep improving!

  • Проголосовать: нравится
  • -26
  • Проголосовать: не нравится

»
4 недели назад, скрыть # |
 
Проголосовать: нравится +16 Проголосовать: не нравится

Nah optimal is n^1.9999