Solved Problem - Triplet Sum

Problem statement

Given a sorted array of NN integers A[]A[]. Find if there exists a triplet of integers A[i]A[i], A[j]A[j] and A[k]A[k] such that the sum is equal to given integer XX.

Input format

The first line of input consists of two space-separated integers N(1N105)N(1 \leq N \leq 10^{5}) and X(1X106)X(1 \leq X \leq 10^{6}).

The next line contains NN space-separated integers representing the array A[](1A[i]105)A[](1 \leq A[i] \leq 10^{5}).

Output format

Print a single line of three space-separated integers ii, jj and kk such that A[i]+A[j]+A[k]=XA[i] + A[j] + A[k] = X or print 1-1 if there is no such triplet.


Sample

Input

6 35
2 4 7 10 15 16

Output

2 5 6

Explanation

2nd2^{nd}, 5th5^{th} and 6th6^{th} element of A[]A[] add upto 3535.

A[2]=4A[2] = 4

A[5]=15A[5] = 15

A[6]=16A[6] = 16


Brute force

Use three loops to iterate over the array and check all (N3){N} \choose {3} pairs. Time complexity is O(N3)O(N^{3}).


Optimize to O(N2)O(N^{2})

The algorithm is a slight modification of the Pair sum problem discussed earlier. If we iterate over the array for ii then we need to find a pair in the array A[i+1...N]A[i+1...N] that adds to XA[i]X-A[i].

The second part is exactly the previous problem.

Get hands-on with 1200+ tech skills courses.