Link to code : https://ide.codingblocks.com/s/289607
Triplate Sum
Corner case missing
hello @reshusinghhh
ur logic is not correct.
u have to print all triplets.
For the sample case, Array = {5, 7, 9, 1, 2, 4, 6 ,8 ,3}. Target number = 10.
Find any three numbers in the given array whose sum is equal to the target number. In this case triplets are:
1, 2 and 7
1, 3 and 6
1, 4 and 5
2, 3 and 5
Algorithm:
1.Sort the element in ascending order
- Start a loop from i=0 to i<n. We mark arr[i] at each instance as a fixed element for that iteration and work to find a pair of elements such that their sum is equal to target-arr[i] hence ensuring that the net sum of the three elements would be equal to target.
- Inside this loop, implement the two pointer approach. Keep a left pointer starting from i+1 and a right pointer from n-1.
- Work an inner left till left<right. For each iteration , check whether a[i] + a[left] + a[right] == target. If so ,print the triplet. Else if this sum = a[i] + a[left] + a[right] is less than the target , then increment the left pointer by one. Else decrement the right pointer by one.
3.Thus, all the triplets have been printed.