4Sum

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given an array nums of n integers and an integer target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • a, b, c, and d are distinct indices
  • nums[a] + nums[b] + nums[c] + nums[d] == target

The solution set must not contain duplicate quadruplets. You may return the answer in any order.

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 three distinct quadruplets that sum to 0 are [-2,-1,1,2], [-2,0,0,2], and [-1,0,0,1].

Example 2:

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

Output: [[2,2,2,2]]

Explanation: The only unique quadruplet that sums to 8 is [2,2,2,2].

Example 3:

Input: nums = [-3,-1,0,2,4,5], target = 2

Output: [[-3,-1,2,4]]

Explanation: The only quadruplet that sums to 2 is [-3,-1,2,4].

Constraints

  • 1 <= nums.length <= 200
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle