3 Sum Variation
Anonymous User
1475

Given an array of n integers arr, and a sum k, you need to return count of triplets with the sum k(Duplicate triplets are allowed).

arr[] : {1,3,2,4,1,3,4,2}, k = 5
Output: 4 //{1,2,2}, {2,1,2}, {1,3,1}, {1,1,3}
above 4 Outputs does not include permutations, its 4 times because every time we are considering different index of elements. (1,2 and 3 appear twice, so considering different indices everytime, we get output 4)

I tried 2Sum Approach using HashTable but I am a bit confused when should I insert in HashTable, because the 2Sum Approach I follow is:

int twoSums(int nums[], int n, int k){
	int count = 0;
	unordered_set<int> hashSet;
	for(int i = 0; i < n;i++){
		//if Sum - currElement is present in hashset
		if(hashSet.find(k - nums[i]) != hashSet.end())
			count++;
		//Once this element is checked, now add to hashSet
		hashSet.insert(nums[i]);
	}
	return  count;
}
Comments (6)