Problem 317120 · hard · Level 03 Linear Management & Searching

Unique Quadruples With a Given Sum

two pointers · sorting · k-sum · deduplication

Given a list of integers nums and an integer target, return all distinct quadruples [a, b, c, d] (values taken from four different indices) with a + b + c + d == target. Each quadruple must be sorted in non-decreasing order; the order of quadruples in the output does not matter.

Examples

Input:  nums = [2, -3, 1, -1, 1, 3], target = 1
Output: [[-3, -1, 2, 3], [-3, 1, 1, 2]]

Input:  nums = [3, 3, 3, 3, 3], target = 12
Output: [[3, 3, 3, 3]]

Constraints

  • 0 <= len(nums) <= 300, -10**9 <= nums[i] <= 10**9
  • Target: O(n^3) time, O(1) extra space beyond the output.

Goals

  • Nest two fixed indices around a converging two-pointer scan
  • Skip duplicate values at every level so each quadruple is reported once
Starting Python…