« Triplet sum
Problem
You have been given a random integer array/list(ARR) and a number X. Find and return the triplet(s) in the array/list which sum to X.
Note :
Given array/list can contain duplicate elements.
Input format :
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
First line of each test case or query contains an integer 'N' representing the size of the first array/list.
Second line contains 'N' single space separated integers representing the elements in the array/list.
Third line contains an integer 'X'.
Output format :
For each test case, print the total number of triplets present in the array/list.
Output for every test case will be printed in a separate line.
Constraints :
1 <= t <= 10^2
0 <= N <= 10^3
0 <= X <= 10^9
Time Limit: 1 sec
Sample Input 1:
1
7
1 2 3 4 5 6 7
12
Sample Output 1:
5
Sample Input 2:
2
7
1 2 3 4 5 6 7
19
9
2 -5 8 -6 0 5 10 11 -3
10
Sample Output 2:
0
5
Explanation for Input 2:
Since there doesn't exist any triplet with sum equal to 19 for the first query, we print 0.
For the second query, we have 5 triplets in total that sum up to 10. They are, (2, 8, 0), (2, 11, -3), (-5, 5, 10), (8, 5, -3) and (-6, 5, 11)
Solution
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int tripletSum(int *arr, int n, int num)15{16 int ans = 0;1718 sort(arr, arr + n);1920 for (int i = 0; i < n - 2; i++)21 {22 int curr_sum = num - arr[i];23 int j = i + 1;24 int k = n - 1;2526 while (k > j)27 {28 if (arr[j] + arr[k] > curr_sum)29 {30 k--;31 }32 else if (arr[j] + arr[k] < curr_sum)33 {34 j++;35 }36 else37 {38 int elementAtStart = arr[j];39 int elementAtEnd = arr[k];4041 if (elementAtStart == elementAtEnd)42 {43 int totalElementsFromStartToEnd = (k - j) + 1;44 ans = ans + ((totalElementsFromStartToEnd * (totalElementsFromStartToEnd - 1)) / 2);45 break;46 }4748 int tempStart = j + 1;49 int tempEnd = k - 1;5051 while (arr[tempStart] == elementAtStart)52 {53 tempStart++;54 }5556 while (arr[tempEnd] == elementAtEnd)57 {58 tempEnd--;59 }6061 int totalElementsFromStart = (tempStart - j);62 int totalElementsFromEnd = (k - tempEnd);6364 ans = ans + (totalElementsFromStart * totalElementsFromEnd);6566 j = tempStart;67 k = tempEnd;68 }69 }70 }7172 return ans;73}7475int main()76{77 int t;78 cin >> t;7980 while (t > 0)81 {82 int size;83 int x;84 cin >> size;8586 int *input = new int[size];8788 for (int i = 0; i < size; i++)89 {90 cin >> input[i];91 }92 cin >> x;9394 cout << tripletSum(input, size, x) << endl;9596 delete[] input;97 t--;98 }99100 return 0;101}