4 Sum - Find a quadruplet with closest sum in C++22 Mar 2025 | 12 min read The 4 Sum (Find a quadruplet with the closest sum) problem falls under the category of k-Sum problems, which are all related to finding a set of numbers that would sum up to a target or nearly a target. Here, the problem is to determine four numbers (a quadruplet) in each of the arrays where the sum is equal to a certain given number as closely as possible. To get rid of this issue, useful sorting algorithms such as sorting and two-pointer methodology are normally implemented to cut the time complexity. The first two numbers can be fixed with two loops when the array is sorted, and the other two numbers can be easily fixed using the two-pointer technique, which ultimately makes the complexity of the problem equal to O(n^3). The sorted array can help in the structured search for combinations, and two pointers can be used to control the process depending on the sum of the current quadruplet to search for the value close to the target sum. The aim is to keep following the sum that comes as close as possible to the aim as we optimizes the sum in a process. Whenever a better quadruplet sum that is closer to the target is obtained, it replaces those found before. As soon as the precise amount equalling the goal is discovered, the search may be stopped because there will not be a superior solution. This problem is another good practice of optimizing techniques such as sorting and the two-pointer method in addition to forcing to get the solution in the language most efficiently. The problem also shows that when working with larger datasets, appropriate data structures and algorithms should be applied without the risk of weak performance. Approach-1: Brute-Force ApproachThe brute force method can be regarded as straightforward to implement when approaching the 4 Sum problem, but it is also thoroughly inefficient. In this approach, all the possibilities of adding any 4 elements in the input array are checked to find the right combination that is closest to the given target. Program:Let us take an example to illustrate the 4 sum problem using the Brute-Force Approach in C++. Output: Input array: 1 2 -1 -4 -2 3 0 Target sum: 1 The closest sum to the target 1 is: 1 Input array: 5 3 2 7 8 10 -1 Target sum: 12 The closest sum to the target 12 is: 12 Input array: 0 0 0 0 Target sum: 0 The closest sum to the target 0 is: 0 Input array: 1 1 1 1 1 1 Target sum: 4 The closest sum to the target 4 is: 4 Input array: -1 2 1 -4 3 0 0 -2 Target sum: 1 The closest sum to the target 1 is: 1 Explanation:
Function fourSumClosest:
Nested Loops:
Closest Sum Calculation:
Input Display Function:
Testing Function:
Complexity Analysis:Time Complexity The time complexity of this brute-force method is determined to be O(n^4). This complexity arises from the four nested loops used to iterate through the array:
In this regard, since each Loop relies on the other, the number of combinations being evaluated is a polynomial of the size of the input array, specifically a 4th-order polynomial. Therefore, the numbering of iterations increases with the size of the input, which becomes a critical issue for large datasets and considerably degrades the execution speed. Space Complexity The space complexity of this approach is constant, O(1). It means that the algorithm takes a constant amount of extra space over and above what is required by the input array. The indices_alloc, current_sum and best_sum variables are used to store the indices, current sum, and best sum, and these variables do not increase with the size of the input. Hence, the algorithm does not need auxiliary data structures that have proportional space complexity with the input size, thus being memory efficient. Approach-2: Sorting and Two-Pointer TechniqueOptimizing and choosing the Two-Pointer method is a good solution for the 4 Sum (Find a quadruplet with the closest sum problem). This method cuts down the time complexity in half compared to the above method using the brute force sorting method and the two-pointer method. Program:Let us take an example to illustrate the 4 sum problem using Sorting and Two-Pointer technique in C++. Output: Input array: 1 2 -1 -4 -2 3 0 Target sum: 1 The closest sum to the target 1 is: 1 Input array: 5 3 2 7 8 10 -1 Target sum: 12 The closest sum to the target 12 is: 12 Input array: 0 0 0 0 Target sum: 0 The closest sum to the target 0 is: 0 Input array: 1 1 1 1 1 1 Target sum: 4 The closest sum to the target 4 is: 4 Input array: -1 2 1 -4 3 0 0 -2 Target sum: 1 The closest sum to the target 1 is: 1 Explanation:
Complexity Analysis:Time Complexity:
Space Complexity:
Next TopicMove to Front Algorithm in C++ |
Difference Between RAII and Garbage Collection in C++
RAII (Resource Acquisition Is Initialization) and garbage collection (GC) are two useful techniques, but they are employed in the opposite manner to fulfill the resource management in the programming, especially in managing memory. In this article, we will discuss the difference between RAII and Garbage Collection....
7 min read
Pentatope Number in C++
In this article, we will discuss the Pentatope Numbers with several examples. What is the Pentatope Numbers? The Pentatope Numbers are represented by the fifth number in each row of Pascal's Triangle, beginning with the row that has at least five numbers. Formula: The following is the formula for the...
4 min read
Non-hypotenuse Number in C++
In this article, we are going to discuss Non-hypotenuse numbers in C++. A Non-Hypotenuse Number is a positive integer that cannot be expressed as the hypotenuse of a right-angled triangle with integer sides. Number theory is different because it doesn't work with the Pythagorean theorem...
6 min read
Mutable lambda in C++
Lambda functions in C++ offer a succinct means of defining tiny, private functions. By default, variables from their surrounding scope can be captured by lambda functions either by value or by reference. However, without the mutable keyword, the captured variables cannot be changed. A lambda...
4 min read
Traits in C++
In this article, we will discuss about traits in C++. C++ trait is an interesting function and variable inside of which the features and skills of the class are created for runtime. The Characters, which are no longer a common language feature in object-oriented programming languages,...
3 min read
std::basic_ios::copyfmt in C++
In this article, we will discuss the , including its syntax, examples, benefits, and many others. Introduction: In the C++ global, understanding the details of streams and the mechanics in their formatting is core to streamed I/O. The useful feature is a std::basic_ios::copyfmt from the C++ Standard Library,...
7 min read
std::chi_squared_distribution in C++
Introduction In the world of statistics and probabilities, the Chi-squared (χ²) distribution is a very important concept that has applications in hypothesis testing, confidence interval estimation and goodness-of-fit tests. In C++, we can generate random numbers that follow a Chi-squared distribution through the std::chi_squared_distribution class of the...
9 min read
Find Maximum Profit for Products within Budget in C++
In the dynamic landscape of computer programming, the quest for optimization solutions is a journey that often involves a harmonious blend of algorithmic prowess and a deep understanding of programming languages. One intriguing challenge that frequently emerges is the task of maximizing profits for a set...
10 min read
Difference between Debug and Release Builds in C++
Debug and release builds have varied uses in C++ during the development and deployment phases. Debug a build with extra information such as debug symbols and no code optimization makes it simpler to go through the code, trace errors, and observe variable states. These debugging features...
10 min read
Move to Front Algorithm in C++
Introduction In computer science and programming, data manipulation and reordering are often performed. The Move to Front (MTF) algorithm is an interesting algorithm that is used in reordering elements of a list. MTF is a simple but effective way of rearranging the order of elements according to...
7 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India