FrontendInterviews.dev

Loading problem…

292. 4Sum

Medium•
Acceptance: 63.64%
•
🔓3/3 Pro unlocks today

This problem builds on three-sum. Complete that first, then load your solution to continue.

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

  • 0 <= a, b, c, d < n
  • a, b, c, and d are distinct
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

Extend the 3Sum pattern to find all unique quadruplets that sum to a given target. This requires an additional layer of iteration over the two-pointer technique.

Requirements

1. Basic Functionality

  • Find all unique quadruplets that sum to target
  • No duplicate quadruplets in the result
  • Handle edge cases (fewer than 4 elements, no valid quadruplets)

Example Usage

fourSum([1, 0, -1, 0, -2, 2], 0);
// [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

fourSum([2, 2, 2, 2, 2], 8);
// [[2, 2, 2, 2]]

Real-World Context

  • Portfolio optimization: Finding combinations of assets that meet a target allocation
  • Network routing: Finding groups of nodes that satisfy bandwidth constraints
  • Resource allocation: Distributing resources across teams to meet targets

Constraints

  • 1 <= nums.length <= 200
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9