Good morning! Here's our prompt for today.
The Four Musketeers: Finding Quadruplets in an Array
Let's say you have a treasure chest, represented as an array of integers called nums. Your mission, should you choose to accept it, is to find four unique keys (numbers) from this treasure chest that unlock a magical target value when combined.
In other words, you have to find all unique sets of four integers [nums[a], nums[b], nums[c], nums[d]] such that:
0 < a, b, c, d < length of arraya,b,c, anddare distinct.nums[a] + nums[b] + nums[c] + nums[d] = target
You can present these sets in any order you like!
Examples to Illuminate the Path
Example 1:
Input: Your treasure chest is [1,0,-1,0,-2,2] and the magical target is 0.
Output: The unique sets of keys that unlock the magical target are [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]].
Example 2:
Input: Your treasure chest is [2,2,2,2,2] and the magical target is 8.
Output: The only set of keys that unlock the magical target is [[2,2,2,2]].
Magical Constraints:
- The treasure chest will have between 1 and 200 keys.
- The value of each key and the magical target will range from
-10^9to10^9.

Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx// Function to find all unique quadruplets that add up to the target sum.// FILL OUT YOUR SOLUTION HEREfunction fourSum(nums, target) { // Write your logic here.}​// Utility function to compare two 2D arraysfunction are2DArraysEqual(arr1, arr2) { if (arr1.length !== arr2.length) return false;​ for (let i = 0; i < arr1.length; i++) { if (arr1[i].length !== arr2[i].length) return false;​ for (let j = 0; j < arr1[i].length; j++) { if (arr1[i][j] !== arr2[i][j]) return false; } }​ return true;}​// Test cases to validate your solutionfunction runTests() { // Test Case 1 let testCase1 = fourSum([1, 0, -1, 0, -2, 2], 0); let expected1 = [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]; // You can sort the arrays for easier comparison console.log("Test Case 1: ", are2DArraysEqual(testCase1, expected1) ? "Passed" : "Failed");​ // Test Case 2Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.


