![]() |
VOOZH | about |
You are given an array arr[] of N integers, and your task is to find three values (at distinct positions) whose sum is X.
Note: The indices can be printed in any order.
Examples:
Input: N = 4, X = 8, arr[] = {2, 7, 5, 1}
Output: 1 3 4
Explanation: The elements at position 1, 3 and 4 are: 2, 5 and 1 respectively. Sum of all these elements is 2 + 5 + 1 = 8.Input: N = 4, X = 7, arr[] = {1, 1, 1, 1}
Output: Impossible
Explanation: No three elements from arr[] can have total sum = 7.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Sorting and Two Pointer approach. We can store pairs of values and index of arr[] in a 2D vector, say vec[][]. Sort vec in ascending order of the values. Iterate a loop, say ptr1 from 0 to N - 2, for the first value. We assume that vec[ptr1][0] is the first value and now we need to search for the second and third value. For the second and third value, we can use two pointers(ptr2 and ptr3) on the ends of the remaining subarray (ptr2 = ptr1 + 1, ptr3 = N - 1). Let's say the sum of these three values is currentSum = vec[ptr1][0] + vec[ptr2][0] + vec[ptr3][0]. Now, we can have three cases:
- Case 1: currentSum = X, we got the answer so print vec[ptr1][1], vec[ptr2][1] and vec[ptr3][1].
- Case 2: currentSum < X, this means we want to increase the sum of three value. Since we have assumed that vec[ptr1][0] is the first value, we cannot change ptr1. So the only way to increase the sum is to move ptr2 forward, that is ptr2 = ptr2 + 1.
- Case 3:currentSum > X, this means we want to decrease the sum of three value. Since we have assumed that vec[ptr1][0] is the first value, we cannot change ptr1. So, the only way to decrease the sum is to move ptr3 backward, that is ptr3 = ptr3 - 1.
We keep on moving ptr2 and ptr3 closer till ptr2 < ptr3. If we didn't get any valid triplet ptr1, ptr2 and ptr3 such that vec[ptr1][0] + vec[ptr2][0] + vec[ptr3][0] = X, it means that our assumption that vec[ptr1][0] is the first value is wrong, so we will shift ptr1 to ptr1 + 1 and assume that vec[ptr1][0] is the first value. Again, start finding a valid triplet with sum = X.
If after all the possible assumptions of the first value we do not get any answer, then it is impossible to have sum = X.
Step-by-step algorithm:
Below is the implementation of the algorithm:
4 1 3
Time Complexity: O(N * N), where N is the size of input array arr[].
Auxiliary Space: O(N)