Hi Friend, Please find Algorithm for Q1.
Please repost other questions in separate post.
Please let me knwo in case of any issue in Q1.
Algorithm:
1. First, sort the array.
2. Then, loop over the array with the first pointer i.
3. Now, use a second pointer j to loop up from there and a third pointer k to simultaneously loop down from the end.
Whenever you’re in a situation where A[i]+A[j]+A[k] < X,
you know that the same holds for all j<k'<k so increment your count with k-j and increment j.
I keep the hidden invariant that A[i]+A[j]+A[k+1] >= X,
so incrementing j only makes that statement stronger.
Otherwise, decrement k. When j and k meet, increment i.
You will only increment j and decrement k, so they need O(n) amortized time to meet.
Time Complexity: O(n^2) time:
In pseudocode:
count= 0
for i = 0; i < N; i++
j = i+1
k = N-1
while j < k
if A[i] + A[j] + A[k] < X
count += k-j
j++
else
k–