4 Sum

Medium

Given an arraynumsofn_integers and an integertarget, are there elements_a,b,c, andd_innumssuch that_a+b+c+d=target? Find all unique quadruplets in the array which gives the sum oftarget.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Analysis

All K Sum problem can be divided into two problems:

  • 2 Sum Problem

  • Reduce K Sum problem to K – 1 Sum Problem

从4Sum和3Sum,我们可以看出对于KSum的通用套路:将KSum转化为K-1 Sum,最后用2Sum的Two Pointer求解。

注意要点:先排序,去除/跳过重复元素

Solution

Similar idea to 3 sum, basically reduce to 2sum, adding one more outer loop. And ALWAYS remember to skip duplicates.

Time - O(n^3), Space - O(1); (33 ms, faster than 78.15%)

Generalized K Sum Approach:

Another K Sum

Reference

Generalized KSums: https://leetcode.com/problems/4sum/discuss/8609/My-solution-generalized-for-kSums-in-JAVA

Last updated

Was this helpful?