26. Find All Four Sum Numbers
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
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
and q2
) to fix two numbers.
Use two more pointers (q3
and q4
) 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
from 0 to n - 1
, where n
is the size of arr
.
If q1 > 0
and arr[q1]
is equal to arr[q1 - 1]
, skip this iteration to avoid duplicate results.
The inner loop iterates for q2
from q1+1 to n - 1
.
If q2 > q1 + 1
and arr[q2]
is equal to arr[q2 - 1]
, skip this iteration to avoid duplicate results.
Calculate the remaining two numbers q3
and q4
using two pointers:
Initialize q3 = q2 + 1
and q4 = 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 the out
vector and increment q3
and decrement q4
.
Also, skip duplicates in q3
and q4
to avoid duplicate results.
If the sum is less than k
, increment q3
.
If the sum is greater than k
, decrement q4
.
Return the out
vector containing all unique quadruplets that sum up to k
.
Time Complexity: O(n^3)
- This is because we have three nested loops in the worst case, where n
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.
For discussions, questions, or doubts related to this solution, please visit our . 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 repository.