Prepin
Log in

4-sum problem | Quadruples that total a specified sum

Approach / Explanation

This problem presents you with an array of integers and a target sum. Your objective is to develop an algorithm that identifies all unique quadruplets within the array that add up to the specified target sum. A quadruplet consists of four elements from the array. Keep in mind that quadruplets must be distinct, meaning that even if the same numbers are arranged differently, they do not count as separate quadruplets. To tackle this problem, consider employing techniques from algorithms like the Two Pointers method and Hashing to optimize time complexity. Begin by sorting the array, which will facilitate iterative comparisons and help eliminate duplicate quadruplets.

Suggested Answer

Starting with the array [1, 0, -1, 0, -2, 2] and a target value of 0, we first sort the array and then iterate through each potential pair. We set up two pointers: one at the end of the array and the other right after the fixed pair. We then move the pointers towards each other until they converge, checking if the sum of the numbers indicated by the pointers and the fixed pair equals the target. When such pairs are identified, we record them and continue to search for additional matches. The sorted array is [-2, -1, 0, 0, 1, 2]. The potential quadruplets could include: Pair (-2, 2), pointers (-1, 1), sum = 0 Pair (-2, 1), pointers (-1, 2), sum = 0 Pair (-1, 2), pointers (0, -1), sum = 0 So, the final output would be: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

Alternative Answer

Let's examine the array [-3, -2, -1, 0, 0, 1, 2, 3], where the target sum is 0. We will begin by sorting the array, which remains unchanged in this instance. Possible quadruplets include: Pair (-3, 3) with pointers (-2, 2), yielding a sum of 0 Pair (-3, 2) with pointers (-1, 2), yielding a sum of 0 Pair (-2, 3) with pointers (-1, 0), yielding a sum of 0 Pair (-3, 1) with pointers (0, 2), yielding a sum of 0 This results in the following quadruplets: [[-3, -2, 2, 3], [-3, -1, 0, 3], [-3, 0, 0, 3], [-3, 0, 1, 2], [-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]].

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.