Count Triplets

Easy
0/40
Average time to solve is 15m
profile
Contributed by
24 upvotes
Asked in companies
AmazonPayPalDunzo

Problem statement

You have been given an integer ‘X’ and a non-decreasing sorted doubly linked list with distinct nodes.

Your task is to return the number of triplets in the list that sum up to the value ‘X’.

Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line contains a single integer ‘T’ denoting the number of test cases. The test cases follow.

The first line of each test case contains a single integer ‘X’.

The second line of the input contains the elements of the doubly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
Output Format:
For each test case, print in a new line a single integer denoting the number of triplets that have the sum equal to ‘X’.
Note:
You don’t need to print anything; it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5
1 <= N <= 10 ^ 3
- 3 * 10 ^ 5 <= X <= 3 * 10 ^ 5
- 10 ^ 5 <= data <= 10 ^ 5 and data != - 1

Where ‘N’ is the number of nodes in the given linked list, and ‘X’ is the required triplet sum value.

Time limit: 1 sec
Sample Input 1:
2
13
-4 2 3 8 9 -1
5
-4 -2 3 4 5 -1
Sample Output 1:
2
2
Explanation to Sample Input 1:
In the first test case, there are two possible triplets {2,3,8} and {-4,8,9}, whose sum is 13.
In the second test case there are two triplets possible {-4,4,5} and {-2,3,4} whose sum is 5.
Sample Input 2:
2
-4
-3 8 10 -1
12
1 4 6 2 -1
Sample Output 2:
0
1
Explanation to Sample Input 2:
In the first test case, there is no triplet whose sum is -4.
In the second test case, there is only one triplet {6,4,2}, whose sum is 12.
Hint

Try to explore all the possible triplets.

Approaches (3)
Brute Force

The idea is to explore all the triplets and count those triplets which have a sum equal to ‘X’. We will use a variable 'COUNT' which will be initialized to 0, to count the number of triplets with sum ‘X’. The steps are as follows:

  • We will iterate the linked list and pick each node one by one and pivot that node as the first element of the triplet, let this node be 'FIRSTPTR'.
  • For the second element of the triplet, iterate from the next node of 'FIRSTPTR' till the end of the linked list and one by one pick each node and pivot that, let’s say this node is 'SECONDPTR'. So we will pivot 'SECONDPTR' as the second element of the triplet.
  • For the third element, iterate from the next node of 'SECONDPTR' till the end of the list and pivot each node as the third element.
  • If the sum of the three pivoted nodes is equal to ‘X’ increment 'COUNT' by 1.
Time Complexity

O(N ^ 3), where ‘N’ is the number of nodes in the doubly linked list.

 

For each pivoted node, we are pivoting each node in front of the pivoted node and then exploring all nodes in front of the second pivoted node. So, the overall Time complexity will be O(N ^ 3).

Space Complexity

O(1).

 

We are not using any additional space. So, space complexity will be O(1).

Code Solution
(100% EXP penalty)
Count Triplets
All tags
Sort by
Search icon

Interview problems

3 pointer java solution

public class Solution {

    public static int countAllTripletSum(Node head, int x) {

        // Write your code here.

        Node temp = head;

        int count = 1;

        while(temp!=null && temp.next!=null){

            temp=temp.next;

            count++;

        }

        if(count<=2){

            return 0;

        }

        int curr=0,res=0;

        Node h,t;

        while(head!=temp){

            curr=x-head.data;

            h=head.next;

            t=temp;

            while(h!=t && h.prev!=t){

                if((h.data + t.data) == curr){

                    res++;

                    t=t.prev;

                    h=h.next;

                }else if((h.data + t.data) > curr){

                    t=t.prev;

                }else{

                    h=h.next;

                }

            }

            head=head.next;

        }

        return res;

    }

}

79 views
0 replies
0 upvotes

Interview problems

Simple 3 pointer solution optimize C++ code

int countAllTripletSum(Node *head, int x)

{

    int cnt = 0;

    if(head==NULL)  return cnt;

    Node * right;

    Node*temp = head;

    while(temp->next != NULL){

        temp = temp->next;

    }

   right=temp;

    Node * curr = head;

    while(curr!=NULL && curr->next!=NULL&&curr->next->next!=NULL){

        right = temp;

        Node * left = curr->next;

        int target = x - curr->data;

        while(left!=right){

          int sum= left->data + right->data;

          if(sum==target)

           {

               cnt++;

             right = right->prev;

           }

           else if(sum > target){

               right=right->prev;

               

           }

           else{

                left = left->next;

           }

        }

        curr=curr->next;

    }

    return cnt;

}

datastructures

algorithms

tutorial

beginners

+1 more
273 views
0 replies
0 upvotes

Interview problems

super easy c++ solution(100% perfromance),easy to understand,clean code,O(n2)

#include <bits/stdc++.h>

/***************************************

 

    Following is the Node class already written.


 

    class Node

    {

    public:

        int data;

        Node* next;

        Node* prev;


 

        Node(int data)

        {

            next = NULL; prev=NULL;

            this->data = data;

        }


 

        ~Node()

        {

            if (next != NULL)

            {

                delete next;

            }

        }

    };

 

***************************************/

void solve(Node* left,Node* right,int key,int& ans)

{

    if(left==NULL)

    return; 


 

    while(left!=right)

    {

        if(left->data+right->data==key)

        {

           ans+=1;

           left=left->next;

        }else{

            if(left->data+right->data<key)

            {

                left=left->next;

            }else{

                right=right->prev;

            }

        }

    }

}

 

int countAllTripletSum(Node *head, int x)

{

    if(head==NULL)

    return 0;

    Node* tail=head;

    while(tail->next)

    {

        tail=tail->next;

    }

    int ans=0;

    for(Node* num1=head;  num1;    num1=num1->next)

    {

       solve(num1->next,tail,x-num1->data,ans);

    }


 

    return ans;

}

programming

beginners

tutorial

266 views
0 replies
0 upvotes

Interview problems

Python easy solution using extra space,O(n^2) complexity.

def countAllTripletSum(head, x):
    arr=[]
    while head is not None:
        arr.append(head.data)
        head=head.next
    ans=0
    for i in range(len(arr)-2):
        l=i+1
        j=len(arr)-1
        while l<j:
            if arr[i]+arr[l]+arr[j]==x:
                ans+=1
                l+=1
                j-=1
            elif arr[i]+arr[l]+arr[j]<x:
                l+=1
            
            else:
                j-=1

    return ans
63 views
0 replies
0 upvotes

Interview problems

Most Optimal Solution | C++

#include <bits/stdc++.h> 
int countAllTripletSum(Node *head, int x){
    int count = 0;
    if(head == NULL) return count;

    Node *tail = head;
    while(tail->next) tail = tail->next;

    for(Node *num1 = head;num1->next && num1->next->next;num1=num1->next){
        Node *num2 = num1->next , *num3 = tail;
        int target = x - num1->data;
        while(num2 != num3){
            int currSum = num2->data + num3->data;
            count += (currSum == target);
            if(currSum <= target) num2 = num2->next;
            else num3 = num3->prev;
        }
    }

    return count;
}
203 views
0 replies
1 upvote

Interview problems

C++ || easy || without map || SC : O(1) || TC: O(n^2)

int pairSum(Node * head, int k){
    Node *start=head;
    Node *end=head;
    int cnt=0;
    while(end->next) end=end->next;
    while(start!=end && end->next!=start){
        int sum=start->data + end->data;
        if(sum==k){
            cnt++;
            start=start->next;
            end=end->prev;
        }
        else if(sum<k) start=start->next;
        else end=end->prev;
    }
    return cnt;
}

int countAllTripletSum(Node *head, int x)
{
    // Write your code here.
    Node *start=head;
    Node *end=head;
    int cnt=0;
    unordered_map<int,int> mp;
    
    while(start && start->next){
        int k=x-start->data;
        cnt+=pairSum(start->next,k);
        start=start->next;
    }
    return cnt;
}
158 views
0 replies
1 upvote

Interview problems

c++

int countAllTripletSum(Node *head, int x) {    // Write your code here.    unordered_map<int,int>mp;     Node *curr=head;     int count=0;     while(curr!=NULL){         Node *res=curr->next;         while(res!=NULL){             if(mp.find(x-curr->data-res->data)!=mp.end()){                 count++;                                               }             res=res->next;                      }         mp[curr->data]++;         curr=curr->next;              }          return count; }

Count Triplets

273 views
0 replies
0 upvotes

Interview problems

Count Triplets. Two pointers Approach

Two pointers Approach  with T.C = O(N*N),  S.C = O(N).

 

int countTriplets(struct Node* head, int x)  {     // code here.    vector<int>v;    while(head!=NULL){        v.push_back(head->data);        head=head->next;    }        int count=0;    for(int i=0; i<v.size(); i++){        int s=i+1, e=v.size()-1;        while(s<e){            if(v[i] + v[s] + v[e] > x)                e--;                        else if(v[i] + v[s] + v[e] < x)                s++;                        else{                count++;                s++;                e--;            }            }    }    return count; } 

Count Triplets

454 views
0 replies
0 upvotes

Interview problems

Discussion thread on Interview Problem | Count Triplets

Hey everyone, creating this thread to discuss the interview problem - Count Triplets.

 

Practise this interview question on Coding Ninjas Studio (hyperlinked with the following link): Count Triplets

 

332 views
6 replies
0 upvotes
Full screen
Console