CodingBison

Let us go through some of the 4-Sum related problems that are solved using two-pointer technique.

Problem: 4 Sum

Problem: https://leetcode.com/problems/4sum/

Given an array, how many (a,b,c,d) are there in the array such that a + b + c + d = K? The solution set must not contain duplicate quadruplets.

There are some cool optimizations that focus on target being less than being the smallest *K and target being higher than the highest * K:

Problem: 4 Sum II

Problem: https://leetcode.com/problems/4sum-ii/

Given 4 lists A, B, C, D, how many tuples (i, j, k, l) have A[i] + B[j] + C[k] + D[l] is zero.

A naive solution would be O(N^4). Here, we can use the unique solution to consider lists (A, B) first and then consider lists (C, D). In doing so, we know that we are processing elements uniquely.

This does not apply to "4Sum" since we only one one list. We cannot apply the above here. Let us say, we can, then we can split 4Sum into two lists but what if the 4 elements come from the single list.. So, "4Sum II" is a unique problem since it says that the solution must have one element from each of the list.

Note that this problem is similar to the problem of finding a^3+b^3=c^3+d^3.