#K34487. 4Sum: Find All Unique Quadruplets
4Sum: Find All Unique Quadruplets
4Sum: Find All Unique Quadruplets
You are given an array of integers and a target sum \(S\). Your task is to find all unique quadruplets \( [a, b, c, d] \) in the array such that:
[ a+b+c+d=S ]
Each quadruplet must satisfy the condition \( a \le b \le c \le d \) (i.e. sorted in non-decreasing order). The solution should not include duplicate quadruplets.
Example:
Input: arr = [1, 0, -1, 0, -2, 2], S = 0 Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
It is guaranteed that the answer can be found using an approach with sorting and two-pointer technique.
inputFormat
The input is given via standard input (stdin) in the following format:
- The first line contains two space-separated integers: \( n \) (the number of elements in the array) and the target sum \( S \).
- The second line contains \( n \) space-separated integers representing the array elements.
For example:
6 0 1 0 -1 0 -2 2
outputFormat
Output the list of all unique quadruplets (each quadruplet is a list of 4 integers) that add up to the target sum \( S \). The output must be printed on standard output (stdout) in a Python list format.
If no quadruplets can be found, output an empty list: []
.
6 0
1 0 -1 0 -2 2
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]