medium Quadruple Sum to Target
Problem Statement
Given an array of unsorted numbers and a target number, find all unique quadruplets in it, whose sum is equal to the target number.
Example 1:
Input: [4, 1, 2, -1, 1, -3], target=1
Output: [-3, -1, 1, 4], [-3, 1, 1, 2]
Explanation: Both the quadruplets add up to the target.
Example 2:
Input: [2, 0, -1, 1, -2, 2], target=2
Output: [-2, 0, 2, 2], [-1, 0, 1, 2]
Explanation: Both the quadruplets add up to the target.
Constraints:
1 <= nums.length <= 200- -109 <= nums[i] <= 109
- -109 <= target <= 109
Try it yourself
Try solving this question here:
✅ Solution Quadruple Sum to Target
Problem Statement
Given an array of unsorted numbers and a target number, find all unique quadruplets in it, whose sum is equal to the target number.
Example 1:
Input: [4, 1, 2, -1, 1, -3], target=1
Output: [-3, -1, 1, 4], [-3, 1, 1, 2]
Explanation: Both the quadruplets add up to the target.
Example 2:
Input: [2, 0, -1, 1, -2, 2], target=2
Output: [-2, 0, 2, 2], [-1, 0, 1, 2]
Explanation: Both the quadruplets add up to the target.
Constraints:
1 <= nums.length <= 200- -109 <= nums[i] <= 109
- -109 <= target <= 109
Solution
This problem follows the Two Pointers pattern and shares similarities with "Triplet Sum to Zero".
We can follow a similar approach to iterate through the array, taking one number at a time. At every step during the iteration, we will search for the quadruplets similar to Triplet Sum to Zero whose sum is equal to the given target.
Here's a detailed walkthrough of the algorithm:
-
In
searchQuadruplets, the array is first sorted in ascending order. Sorting is important as it allows us to navigate our pointers based on the sum we're calculating and ensures that the generated quadruplets are in a predictable order. -
A
Listnamedquadrupletsis created to store all the quadruplets found. -
The algorithm then loops over the array, stopping when there are less than four elements remaining (since we need groups of four).
-
If the current element is the same as the previous one (and it's not the first), we skip this iteration to avoid duplicate quadruplets.
-
A nested loop is initiated from the next index of the outer loop. This loop also ensures that the current element isn't the same as the previous one to avoid duplicates.
-
The
searchPairsfunction is called with the array, target value, indices of the first two elements, and thequadrupletslist. This function will find pairs in the array (fromsecond+1index to the end) whose sum witharr[first]andarr[second]equals the target. Any valid quadruplets found are added to thequadrupletslist. -
In
searchPairs, two pointersleftandrightare initialized:lefttosecond+1, andrightto the last element of the array. It then enters a while loop that continues untilleftis less thanright. -
Inside this loop, the sum of the elements at the current four indices (
first,second,left,right) is calculated. If this sum equalstargetSum, a valid quadruplet is found. -
This quadruplet is added to the
quadrupletslist, and bothleftandrightpointers are moved inward. If the next elements are the same as the current elements ofleftandrightrespectively, they are skipped to avoid duplicates. -
If the calculated sum is less than
targetSum,leftis incremented to increase the sum (as the array is sorted), and if the sum is greater thantargetSum,rightis decremented to decrease the sum. -
This process repeats until
leftandrightcross, by which point all possible pairs for the givenfirstandsecondindices have been examined. -
Once
searchPairshas processed all possible pairs for the givenfirstandsecondindices, it returns, and the nested loop insearchQuadrupletscontinues until all possible starting points for quadruplets have been tried. -
Once all possible quadruplets have been considered,
searchQuadrupletsreturns thequadrupletslist.
The main function in the code demonstrates usage of the searchQuadruplets function with two test cases. It runs searchQuadruplets with specified arrays and target sums, printing the results to the console.
Algorithm Walkthrough
Let's walk through the algorithm using the example input [4, 1, 2, -1, 1, -3] with a target of 1.
-
Sort the Array:
- Input:
[4, 1, 2, -1, 1, -3] - Sorted Array:
[-3, -1, 1, 1, 2, 4]
- Input:
-
Initialize Result List:
quadruplets = []
-
First Loop (
i = 0):- Current Element (
arr[i] = -3) - Second Loop (
j = 1):- Current Element (
arr[j] = -1) - Two Pointers:
left = 2,right = 5
- Current Element (
- Current Element (
-
Two-Pointer Process:
- First Sum Calculation:
sum = arr[0] + arr[1] + arr[2] + arr[5]sum = -3 + (-1) + 1 + 4 = 1- Matches Target: Add
[-3, -1, 1, 4]toquadruplets - Update Pointers:
left = 3right = 4
- Check Duplicates:
- Skip duplicates by moving pointers:
leftmoves to4rightmoves to4
- Skip duplicates by moving pointers:
- Second Sum Calculation:
- Pointers Overlap: End of this pair search
- First Sum Calculation:
-
Second Loop (
j = 2):- Current Element (
arr[j] = 1) - Two Pointers:
left = 3,right = 5 - First Sum Calculation:
sum = arr[0] + arr[2] + arr[3] + arr[5]sum = -3 + 1 + 1 + 4 = 3- Greater Than Target: Move
rightpointer leftright = 4
- Second Sum Calculation:
sum = arr[0] + arr[2] + arr[3] + arr[4]sum = -3 + 1 + 1 + 2 = 1- Matches Target: Add
[-3, 1, 1, 2]toquadruplets - Update Pointers:
left = 4right = 3
- Check Duplicates:
- Skip duplicates by moving pointers:
leftmoves to4rightmoves to3
- Skip duplicates by moving pointers:
- Pointers Overlap: End of this pair search
- Current Element (
-
Second Loop (
j = 3):- Current Element (
arr[j] = 1) (Duplicate) - Skip this element to avoid duplicates.
- Current Element (
-
First Loop (
i = 1):- Current Element (
arr[i] = -1) - Second Loop (
j = 2):- Current Element (
arr[j] = 1) - Two Pointers:
left = 3,right = 5
- Current Element (
- First Sum Calculation:
sum = arr[1] + arr[2] + arr[3] + arr[5]sum = -1 + 1 + 1 + 4 = 5- Greater Than Target: Move
rightpointer leftright = 4
- Second Sum Calculation:
sum = arr[1] + arr[2] + arr[3] + arr[4]sum = -1 + 1 + 1 + 2 = 3- Greater Than Target: Move
rightpointer leftright = 3
- Pointers Overlap: End of this pair search
- Current Element (
-
Second Loop (
j = 3):- Current Element (
arr[j] = 1) (Duplicate) - Skip this element to avoid duplicates.
- Current Element (
-
First Loop (
i = 2):- Current Element (
arr[i] = 1) - Second Loop (
j = 3):- Current Element (
arr[j] = 1) (Duplicate)
- Current Element (
- Skip this element to avoid duplicates.
- Current Element (
- Final Result: The unique quadruplets are
[[ -3, -1, 1, 4], [-3, 1, 1, 2]].
Let's walkthrough the example 1 through diagram below.
Code
Here is what our algorithm will look like:
import java.util.*;
class Solution {
public List<List<Integer>> searchQuadruplets(int[] arr, int target) {
Arrays.sort(arr);
List<List<Integer>> quadruplets = new ArrayList<>();
for (int i = 0; i < arr.length - 3; i++) {
// skip same element to avoid duplicate quadruplets
if (i > 0 && arr[i] == arr[i - 1]) continue;
for (int j = i + 1; j < arr.length - 2; j++) {
// skip same element to avoid duplicate quadruplets
if (j > i + 1 && arr[j] == arr[j - 1]) continue;
searchPairs(arr, target, i, j, quadruplets);
}
}
return quadruplets;
}
private static void searchPairs(
int[] arr,
int targetSum,
int first,
int second,
List<List<Integer>> quadruplets
) {
int left = second + 1;
int right = arr.length - 1;
while (left < right) {
// Use long to handle potential overflow
long sum = (long) arr[first] + arr[second] + arr[left] + arr[right];
if (sum == targetSum) { // found the quadruplet
quadruplets.add(
Arrays.asList(arr[first], arr[second], arr[left], arr[right])
);
left++;
right--;
while (left < right && arr[left] == arr[left - 1]) left++; // skip same element to avoid duplicate quadruplets
while (left < right && arr[right] == arr[right + 1]) right--; // skip same element to avoid duplicate quadruplets
} else if (sum < targetSum) left++; // we need a pair with a bigger sum
else right--; // we need a pair with a smaller sum
}
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(
sol.searchQuadruplets(new int[] { 4, 1, 2, -1, 1, -3 }, 1)
);
System.out.println(
sol.searchQuadruplets(new int[] { 2, 0, -1, 1, -2, 2 }, 2)
);
}
}
Complexity Analysis
Time Complexity
-
Sorting the array: The algorithm begins by sorting the input array, which takes
, where Nis the number of elements in the array. -
Outer loop (i): The first loop runs from
i = 0toi = N-4(i.e., up to the fourth-to-last element in the array). This loop runstimes. -
Second loop (j): The second loop runs from
j = i + 1toj = N-3(i.e., up to the third-to-last element in the array). This loop also runstimes for each iteration of the first loop. -
Two-pointer search (left and right): For each iteration of the second loop, the two-pointer technique is used to find the remaining two numbers. The two-pointer search takes
time in the worst case.
Overall time complexity: The total time complexity is
Space Complexity
-
Sorting the array: Sorting requires additional space which is uses
. -
Resultant quadruplets storage: The algorithm uses a list
quadrupletsto store the resulting quadruplets. In the worst case, there can bequadruplets if many valid quadruplets are found. -
Auxiliary space: A few additional variables (
i,j,left,right, etc.) are used, which require constant space.
Overall space complexity: The space complexity for storing the result is K is the number of quadruplets, and
🤖 Don't fully get this? Learn it with Claude
Stuck on Quadruple Sum to Target? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Quadruple Sum to Target** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Quadruple Sum to Target** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Quadruple Sum to Target**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Quadruple Sum to Target**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.