Count Triplets | Practice | GeeksforGeeks

Given a sorted linked list of distinct nodes (no two nodes have the same data) and an integer X. Count distinct triplets in the list that sum up to given integer X.
Note: The Linked List can be sorted in any order.
Example 1:
Input: LinkedList: 1->2->4->5->6->8->9, X = 17
Output: 2
Explanation: Distinct triplets are (2, 6, 9) 
and (4, 5, 8) which have sum equal to X i.e 17.

Example 2:
Input: LinkedList: 1->2->4->5->6->8->9, X = 15
Output: 5
Explanation: (1, 5, 9), (1, 6, 8), (2, 4, 9), 
(2, 5, 8), (4, 5, 6) are the distinct triplets

Your Task:  
You don't need to read input or print anything. Complete the function countTriplets() which takes a head reference and X as input parameters and returns the triplet count
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ Number of Nodes ≤ 103 
1 ≤ Node value ≤ 104
0
vikasrajpoot4794 days ago
//Using two pointer approach
int solve(vector<int>arr,int x){   sort(arr.begin(),arr.end());      int count=0;   for(int i=0;i<arr.size();i++)   {       int check=arr[i];       int j=i+1;       int k=arr.size()-1;       while(j<k)       {           if(check+arr[j]+arr[k]==x)           {               count++;               j++;               k--;           }           else if(check+arr[j]+arr[k]<x)           {               j++;           }           else{               k--;           }       }   }   return count;}int countTriplets(struct Node* head, int x) { Node*temp=head;vector<int>a;while(temp!=NULL){    a.push_back(temp->data);    temp=temp->next;}int ans=solve(a,x);return ans;}
+1
hr061 month ago
int total(struct Node* head)
{
   int counter = 0;
   Node* curr = head;
   
   while(curr != NULL)
   {
       counter++;
       curr = curr->next;
   }
   
   return counter;
}
int countTriplets(struct Node* head, int K) 
{ 
   // code here.
   // push all the elements in an array
   int n = total(head);
   int arr[n];   // dynamically allocating an array
   
   Node* curr = head;
   
   int itr = 0;
   while(curr != NULL)
   {
       arr[itr++] = curr->data;
       curr = curr->next;
   }
   
   sort(arr,arr+n);
   
   vector<vector<int>> ans;
   
   for(int i = 0; i<n; i++)
   {
       
       int target = K - arr[i];
       int start = i + 1;
       int end = n - 1;
       
       while(start < end)
       {
           int sum = arr[start] + arr[end];
           
           if(sum < target)
           {
               start++;
           }
           else if(sum > target)
           {
               end--;
           }
           else
           {
               int x = arr[start];
               int y = arr[end];
               
               ans.push_back({arr[i], arr[start], arr[end]});
               
               //for getting different value of triplet 
               
               while(start < end && arr[start] == x)
               {
                   start++;
               }
               
               while(start < end && arr[end] == y)
               {
                   end--;
               }
           }
       }
       
       while(i+1 < n && arr[i] == arr[i+1] )
       {
           i++;
       }
      
   }
   
   return ans.size();
   
}
0
gupta2411sumit1 month ago
// Easy Solution C++ 
int countTriplets(struct Node* head, int x) {    // code here.  struct Node *p = head ;    vector<int>v ;    while(p!=NULL)  {      v.push_back(p->data) ;      p = p->next  ;  }    int count = 0 ;    int n = v.size() ;    for( int i = 0 ; i<n-3 ; i++)  {      int l = i+1 ;      int r = n-1  ;            while(l<r)      {          int sum = v[i] + v[l] + v[r] ;                    if(sum<x)          {              l++ ;          }          else if(sum>x)          {              r-- ;          }          else{              count++ ;              l++ ;              r-- ;          }      }  }    return count ;} 
0
mridulbhaskarabc2 months ago
#Time taken: 2.5/14.6
def countTriplets(head,x):
    # code here
    new_node = head
    node_ref = head
    count = 1
    counter = 0
    
    while(new_node.nxt!=None):
        count +=1
        new_node = new_node.nxt
    new_list = [0]*count
    
    
    for i in range(count):
        new_list[i]= node_ref.val
        node_ref = node_ref.nxt
    new_list.sort()
    for i in range(count):
        low = i+1
        high = count-1
        while (low<high):
            sum = new_list[i]+new_list[low]+new_list[high]
            if(sum == x):
                counter+=1
                low+=1
                high-=1
            elif(sum>x):
                high-=1
            else:
                low+=1
                
    return counter
#Contributed By: Mridul Bhaskar
-1
imranwahid4 months ago
Easy C++ solution using two pointer approach
 
+1
shyamprakash8075 months ago
def countTriplets(head,x):   # code here   d = dict()   d1 = dict()   curr = head   while curr != None:       d[curr.val] = True       curr = curr.nxt   curr = head   c = 0   while curr != None:       d[curr.val] -= 1       temp = curr.nxt       while temp != None:           d[temp.val] -= 1           if d.get(x - curr.val - temp.val,False):               l = [curr.val,temp.val,x-curr.val-temp.val]               l.sort()               l = tuple(l)               if d1.get(l,0)==0:                   c += 1                   d1[l] = 1           d[temp.val] += 1           temp = temp.nxt       d[curr.val] += 1       curr = curr.nxt   return c
+1
vijayvargiyarishabh5 months ago
//very easy to understand solution using maps with the time complexity of O(n2) and space O(n). 
 
int countTriplets(struct Node* head, int x) {    // code here.   int ans=0;   unordered_map<int, bool> m;   struct Node* temp1=head;   struct Node* temp2=head;   while(temp1!=NULL)   {       m[temp1->data]=true;       temp1=temp1->next;   }   temp1=head;   while(temp1!=NULL)   {       int a=temp1->data;       temp2=temp1->next;       while(temp2!=NULL)       {           int b=temp2->data;           int t=x-(a+b);
 
   // This if statement is important because it will avoid repeating cases              if(m[t] and t!=a and t!=b and t>a and t>b) ans++;           temp2=temp2->next;       }       temp1=temp1->next;   }   return ans;} 
0
dflag445 months ago
int countTriplets(struct Node* head, int x) {    if(!head)return 0;   stack<int>st;   int count=0;   Node*n1=head;   while(n1)   {       st.push(n1->data);       n1=n1->next;   }   Node*rev=new Node(st.top());   st.pop();   Node*tmp=rev;   while(!st.empty())   {       tmp->next=new Node(st.top());       st.pop();       tmp=tmp->next;   }      n1=head;   while(n1->next->next)   {       Node*n2=n1->next;       Node*n3=rev;       while(n2->data<n3->data){           int sum=n1->data+n2->data+n3->data;           if(sum==x)           {               count++;               n2=n2->next;               //break;           }           else if(sum>x)n3=n3->next;           else if(sum<x)n2=n2->next;       }       n1=n1->next;   }   return count;         } 
0
sunil gudivada 15 months ago
Java Solution with clear explanation
 
 
class Solve
{
    static int countTriplets(Node head, int x) 
    {         
        // Convert linkedList to arraylist
        ArrayList<Integer> list = new ArrayList<>();
        while(head!= null){
            list.add(head.data);
            head = head.next;
        }
        
        int res = 0;
        
        // Sort the elements
        Collections.sort(list);
        
        for(int i=0;i<list.size()-2;i++){
            
            // HashSet to maintain if the required sum exist in the 
            HashSet<Integer> set = new HashSet<>();
            
            // From this problem reduced to 2 Sum Problem
            int sum = x - list.get(i);
            
            // Check the two sum problem from the 1 element next to i
            for(int j=i+1;j<list.size();j++){
                int current = list.get(j);
                
                // If set contains our required sum, increment the result.
                if(set.contains(sum-current)){
                    res++;
                }
                
                // Add the current element to the set
                set.add(current);
            }
            
            // additional step to clear the set after the iteration
            set.clear();
        }
        
        return res;
    } 
}
 
+2
tushargupta19995 months ago
int countTriplets(struct Node* head, int x) { 
    unordered_set<int> seen;
    int ans = 0;
    for(auto a=head; a; a = a->next) {
        for(auto b=a->next; b; b = b->next) {
            if(seen.find(x - a->data - b->data) != seen.end()) ans++;
        }
        seen.insert(a->data);
    }
    return ans;
} 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.