26. Find All Four Sum Numbers
The problem can be found at the following link: Question Link
My Approach
To find all four sum numbers in the given array, by intuition these are the task we need to do.
Sort the input array.
Iterate through the array with two pointers (
q1
andq2
) to fix two numbers.Use two more pointers (
q3
andq4
) to find the remaining two numbers such that their sum equals the target (k
).Handle duplicates to avoid duplicate solutions.
To do so, I follow these steps.
Sort the input array
arr
in ascending order.Initialize an empty vector
out
to store the result.Use two nested loops to select the first two elements of the quadruplet:
The outer loop iterates for
q1
from0 to n - 1
, wheren
is the size ofarr
.If
q1 > 0
andarr[q1]
is equal toarr[q1 - 1]
, skip this iteration to avoid duplicate results.
The inner loop iterates for
q2
fromq1+1 to n - 1
.If
q2 > q1 + 1
andarr[q2]
is equal toarr[q2 - 1]
, skip this iteration to avoid duplicate results.Calculate the remaining two numbers
q3
andq4
using two pointers:Initialize
q3 = q2 + 1
andq4 = n - 1
.While
q3 < q4
, calculate the sum of the current quadruplet(arr[q1] + arr[q2] + arr[q3] + arr[q4])
.If the sum is equal to
k
, add the quadruplet to theout
vector and incrementq3
and decrementq4
.Also, skip duplicates in
q3
andq4
to avoid duplicate results.
If the sum is less than
k
, incrementq3
.If the sum is greater than
k
, decrementq4
.
Return the
out
vector containing all unique quadruplets that sum up tok
.
Time and Auxiliary Space Complexity
Time Complexity:
O(n^3)
- This is because we have three nested loops in the worst case, wheren
is the length of the input array.Auxiliary Space Complexity:
O(1)
- We use only a constant amount of space for variables and the output vector.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated