Problem 317120 · hard · Phase 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 = [1, 0, -1, 0, -2, 2], target = 0
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

Input:  nums = [2, 2, 2, 2, 2], target = 8
Output: [[2, 2, 2, 2]]

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…