Hone logo
Hone
Problems

Finding Quadruplets That Sum to a Target

This challenge involves finding all unique combinations of four numbers within a given array that add up to a specific target sum. This problem is a common variation of the "k-Sum" problem and is fundamental in understanding how to efficiently search for combinations within datasets, applicable in areas like data analysis and algorithm optimization.

Problem Description

Given an array of integers nums and an integer target, your task is to find all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that a, b, c, and d are distinct indices, and nums[a] + nums[b] + nums[c] + nums[d] == target.

Key Requirements:

  • Uniqueness: The solution set must not contain duplicate quadruplets. For example, if nums = [1, 0, -1, 0, -2, 2] and target = 0, the quadruplet [-1, 0, 0, 1] is the same as [0, -1, 0, 1] and should only be included once.
  • Distinct Indices: The four elements in each quadruplet must come from distinct positions in the input array.
  • Return Value: The output should be a list of lists, where each inner list represents a unique quadruplet. The order of quadruplets in the output list does not matter, nor does the order of elements within each quadruplet.

Edge Cases to Consider:

  • An empty input array.
  • An array with fewer than four elements.
  • Scenarios where no quadruplets sum to the target.
  • Arrays containing duplicate numbers.
  • Arrays with negative numbers.

Examples

Example 1:

Input: nums = [1, 0, -1, 0, -2, 2], target = 0
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Explanation:
The quadruplets that sum to 0 are:
(-2) + (-1) + 1 + 2 = 0
(-2) + 0 + 0 + 2 = 0
(-1) + 0 + 0 + 1 = 0

Example 2:

Input: nums = [2, 2, 2, 2, 2], target = 8
Output: [[2, 2, 2, 2]]
Explanation:
The only unique quadruplet is [2, 2, 2, 2] where all elements are chosen from different indices.

Example 3:

Input: nums = [1, 2, 3, 4, 5], target = 100
Output: []
Explanation:
No combination of four numbers from the array sums to 100.

Constraints

  • 1 <= nums.length <= 200
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • The input nums will be an array of integers.
  • The output should be a list of lists of integers.
  • Consider solutions that aim for a time complexity better than O(n^4).

Notes

  • Sorting the input array can be a very helpful first step for dealing with duplicate numbers and for optimizing the search process.
  • Think about how to avoid redundant calculations and how to efficiently check for unique combinations.
  • Consider using a two-pointer approach or a similar technique to find pairs or triplets that, when combined with other elements, meet the target sum.
Loading editor...
plaintext