Open In App

Count triplets in a sorted doubly linked list whose sum is equal to a given value x

Last Updated : 04 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted doubly linked list of distinct nodes and a value x. The task is to count the number of triplets in the list that sum up to a given value x.

Examples:

Input:

Count-triplets-in-a-sorted-doubly-linked-list-whose-sum-is-equal-to-a-given-value-x-2


Output: 0
Explanation: No triplets are present in the above linked list that sum up to a given value x.

Input:

Count-triplets-in-a-sorted-doubly-linked-list-whose-sum-is-equal-to-a-given-value-x-1

Output: 1
Explanation: Only one triplet is present in the above linked list that sum up to a given value x. i.e. (1, 3, 4)

[Naive Approach] Using three nested loops – O(n^3) Time and O(1) Space

The approach involves generating all possible triplets from the sorted doubly linked list and checking if the sum of the three nodes values equals the given target x.

C++
// C++ implementation to count triplets
// in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *next, *prev;

    Node(int val) {
        data = val;
        next = nullptr;
        prev = nullptr;
    }
};

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(Node *head, int x) {
  
    Node *ptr1, *ptr2, *ptr3;
    int count = 0;

    // generate all possible triplets
    for (ptr1 = head; ptr1 != nullptr; ptr1 = ptr1->next)
        for (ptr2 = ptr1->next; ptr2 != nullptr; ptr2 = ptr2->next)
            for (ptr3 = ptr2->next; ptr3 != nullptr; ptr3 = ptr3->next)

                // if elements in the current triplet
              	// sum up to 'x'
                if ((ptr1->data + ptr2->data + ptr3->data) == x)

                    // increment count
                    count++;

    // required count of triplets
    return count;
}

int main() {

	// Create a hard-coded doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->prev = head;
    head->next->next = new Node(3);
    head->next->next->prev = head->next;
    head->next->next->next = new Node(4);
    head->next->next->next->prev = head->next->next;

    int x = 8;
    cout << countTriplets(head, x);
    return 0;
}
C
// C implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
    struct Node *prev;
};

// function to count triplets
// in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node *head, int x) {
    struct Node *ptr1, *ptr2, *ptr3;
    int count = 0;

    // generate all possible triplets
    for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
        for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next)
            for (ptr3 = ptr2->next; ptr3 != NULL; ptr3 = ptr3->next)

                // if elements in the current triplet sum up to 'x'
                if ((ptr1->data + ptr2->data + ptr3->data) == x)

                    // increment count
                    count++;

    // required count of triplets
    return count;
}

struct Node *createNode(int new_data) { 
    struct Node *new_node = 
      (struct Node *)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    new_node->prev = NULL;
    return new_node;
}

int main() {

     // Create a hrad-coded doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4
    struct Node *head = createNode(1);
    head->next = createNode(2);
    head->next->prev = head;
    head->next->next = createNode(3);
    head->next->next->prev = head->next;
    head->next->next->next = createNode(4);
    head->next->next->next->prev = head->next->next;

    int x = 8;

    printf("%d", countTriplets(head, x));

    return 0;
}
Java
// Java implementation to count triplets
// in a sorted doubly linked list
// whose sum is equal to a given value 'x'

class Node {
    int data;
    Node next, prev;

    Node(int d) {
        data = d;
        next = prev = null;
    }
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
class GfG {

    static int countTriplets(Node head, int x) {

        Node ptr1, ptr2, ptr3;
        int count = 0;

        // generate all possible triplets
        for (ptr1 = head; ptr1 != null; ptr1 = ptr1.next)
            for (ptr2 = ptr1.next; ptr2 != null;
                 ptr2 = ptr2.next)
                for (ptr3 = ptr2.next; ptr3 != null;
                     ptr3 = ptr3.next)

                    // if elements in the current triplet
                    // sum up to 'x'
                    if ((ptr1.data + ptr2.data + ptr3.data)
                        == x)

                        // increment count
                        count++;

        // required count of triplets
        return count;
    }

    public static void main(String[] args) {
      
		 // Manually create a doubly linked list:
        // 1 <-> 2 <-> 3 <-> 4
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.prev = head;
        head.next.next = new Node(3);
        head.next.next.prev = head.next;
        head.next.next.next = new Node(4);
        head.next.next.next.prev = head.next.next;

        int x = 8;

        System.out.println(countTriplets(head, x));
    }
}
Python
# Python implementation to count triplets
# in a sorted doubly linked list
# whose sum is equal to a given value 'x'

class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None

# function to count triplets in a sorted doubly linked list
# whose sum is equal to a given value 'x'

def count_triplets(head, x):
    ptr1 = head
    count = 0

    # generate all possible triplets
    while ptr1 is not None:
        ptr2 = ptr1.next
        while ptr2 is not None:
            ptr3 = ptr2.next
            while ptr3 is not None:

                # if elements in the current triplet sum up to 'x'
                if (ptr1.data + ptr2.data + ptr3.data) == x:

                    # increment count
                    count += 1
                ptr3 = ptr3.next
            ptr2 = ptr2.next
        ptr1 = ptr1.next

    # required count of triplets
    return count


if __name__ == "__main__":

    # Create a hard-coded doubly linked list:
    # 1 <-> 2 <-> 3 <-> 4
    head = Node(1)
    head.next = Node(2)
    head.next.prev = head
    head.next.next = Node(3)
    head.next.next.prev = head.next
    head.next.next.next = Node(4)
    head.next.next.next.prev = head.next.next

    x = 8
    print(count_triplets(head, x))
C#
// C# implementation to count triplets in a sorted doubly
// linked list whose sum is equal to a given value 'x'
using System;

class Node {
    public int Data;
    public Node Next;
    public Node Prev;

    public Node(int val) {
        Data = val;
        Next = null;
        Prev = null;
    }
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
class GfG {
    static int CountTriplets(Node head, int x) {
        Node ptr1, ptr2, ptr3;
        int count = 0;

        // generate all possible triplets
        for (ptr1 = head; ptr1 != null; ptr1 = ptr1.Next)
            for (ptr2 = ptr1.Next; ptr2 != null;
                 ptr2 = ptr2.Next)
                for (ptr3 = ptr2.Next; ptr3 != null;
                     ptr3 = ptr3.Next)

                    // if elements in the current triplet
                    // sum up to 'x'
                    if ((ptr1.Data + ptr2.Data + ptr3.Data)
                        == x)

                        // increment count
                        count++;

        // required count of triplets
        return count;
    }

    static void Main() {

        // Create a hard-coded doubly linked list:
        // 1 <-> 2 <-> 3 <-> 4
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Prev = head;
        head.Next.Next = new Node(3);
        head.Next.Next.Prev = head.Next;
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Prev = head.Next.Next;

        int x = 8;
        Console.WriteLine(CountTriplets(head, x));
    }
}
JavaScript
// JavaScript implementation to count
// triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
        this.prev = null;
    }
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
function countTriplets(head, x) {
    let ptr1, ptr2, ptr3;
    let count = 0;

    // generate all possible triplets
    for (ptr1 = head; ptr1 !== null; ptr1 = ptr1.next)
        for (ptr2 = ptr1.next; ptr2 !== null;
             ptr2 = ptr2.next)
            for (ptr3 = ptr2.next; ptr3 !== null;
                 ptr3 = ptr3.next)

                // if elements in the current triplet sum up
                // to 'x'
                if ((ptr1.data + ptr2.data + ptr3.data)
                    === x)

                    // increment count
                    count++;

    // required count of triplets
    return count;
}

// Create a hard-coded doubly linked list:
// 1 <-> 2 <-> 3 <-> 4
const head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(4);
head.next.next.next.prev = head.next.next;

let x = 8;
console.log(countTriplets(head, x));

Output
1

[Better Approach] Using hashmap – O(n^2) Time and O(n) Space

The idea is to generate all possible pairs in the list, calculate their y, and check if a node with value (x-y) exists using a hashmap. While doing so, it’s important to ensure that the third node is distinct from the first and second nodes. Finally, we count/3 as the answer, since each triplet is counted three times.

C++
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *next, *prev;

    Node(int val) {
        data = val;
        next = nullptr;
        prev = nullptr;
    }
};

// function to count triplets in a sorted doubly linked
// list whose sum is equal to a given value 'x'
int countTriplets(Node *head, int x) {
    Node *ptr1, *ptr2;
    int count = 0;

    // unordered_map implemented as hash table
    unordered_map<int, Node *> map;

    // insert the <node data, node pointer> tuple in map
    for (Node *ptr = head; ptr != nullptr; ptr = ptr->next)
        map[ptr->data] = ptr;

    // generate all possible pairs
    for (ptr1 = head; ptr1 != nullptr; ptr1 = ptr1->next)
        for (ptr2 = ptr1->next; ptr2 != nullptr; ptr2 = ptr2->next) {

            // pSum - sum of elements in the current pair
            int pSum = ptr1->data + ptr2->data;

            // if 'x-pSum' is present in 'map' and
            // either of the two nodes
            // are not equal to the 'map[x-pSum]' node
            if (map.find(x - pSum) != map.end() && 
                map[x - pSum] != ptr1 && map[x - pSum] != ptr2)

                // increment count
                count++;
        }

    // required count of triplets
    // division by 3 as each triplet is counted 3 times
    return (count / 3);
}

int main() {

    // Create a hard-coded doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->prev = head;
    head->next->next = new Node(3);
    head->next->next->prev = head->next;
    head->next->next->next = new Node(4);
    head->next->next->next->prev = head->next->next;

    int x = 8;
    cout << countTriplets(head, x);
    return 0;
}
Java
// Java implementation to count triplets in a sorted doubly
// linked list whose sum is equal to a given value 'x'
import java.util.HashMap;

class Node {
    int data;
    Node next, prev;

    Node(int d) {
        data = d;
        next = prev = null;
    }
}

// function to count triplets in a sorted doubly linked
// list whose sum is equal to a given value 'x'
class GfG {

    static int countTriplets(Node head, int x) {
        Node ptr1, ptr2;
        int count = 0;

        // HashMap implemented as hash table
        HashMap<Integer, Node> map = new HashMap<>();

        for (Node ptr = head; ptr != null; ptr = ptr.next) {
            map.put(ptr.data, ptr);
        }

        // generate all possible pairs
        for (ptr1 = head; ptr1 != null; ptr1 = ptr1.next) {
            for (ptr2 = ptr1.next; ptr2 != null;
                 ptr2 = ptr2.next) {

                // pSum - sum of elements in
                // the current pair
                int pSum = ptr1.data + ptr2.data;

                // if 'x-pSum' is present in 'map'
                // and either of the two nodes
                // are not equal to the 'map[x-pSum]'
                // node
                if (map.containsKey(x - pSum)
                    && map.get(x - pSum) != ptr1
                    && map.get(x - pSum) != ptr2) {

                    // increment count
                    count++;
                }
            }
        }

        // required count of triplets
        // division by 3 as each triplet is counted 3
        // times
        return (count / 3);
    }

    public static void main(String[] args) {

        // Manually create a doubly linked list:
        // 1 <-> 2 <-> 3 <-> 4
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.prev = head;
        head.next.next = new Node(3);
        head.next.next.prev = head.next;
        head.next.next.next = new Node(4);
        head.next.next.next.prev = head.next.next;

        int x = 8;
        System.out.println(countTriplets(head, x));
    }
}
Python
# Python implementation to count triplets in a sorted doubly linked list
# whose sum is equal to a given value 'x'

class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None

# function to count triplets in a sorted doubly linked list
# whose sum is equal to a given value 'x'

def count_triplets(head, x):
    ptr1 = ptr2 = None
    count = 0

    # dictionary implemented as hash table
    node_map = {}

    # insert the <node data, node pointer>
    # tuple in map
    ptr = head
    while ptr is not None:
        node_map[ptr.data] = ptr
        ptr = ptr.next

    # generate all possible pairs
    ptr1 = head
    while ptr1 is not None:
        ptr2 = ptr1.next
        while ptr2 is not None:

            # p_sum - sum of elements in the current pair
            p_sum = ptr1.data + ptr2.data

            # if 'x-p_sum' is present in 'map' and either of the two nodes
            # are not equal to the 'map[x-p_sum]' node
            if (x - p_sum) in node_map and node_map[x - p_sum] != ptr1 \
            and node_map[x - p_sum] != ptr2:

                # increment count
                count += 1

            ptr2 = ptr2.next
        ptr1 = ptr1.next

    # required count of triplets
    # division by 3 as each triplet is counted 3 times
    return count // 3


if __name__ == "__main__":

    # Create a hard-coded doubly linked list:
    # 1 <-> 2 <-> 3 <-> 4
    head = Node(1)
    head.next = Node(2)
    head.next.prev = head
    head.next.next = Node(3)
    head.next.next.prev = head.next
    head.next.next.next = Node(4)
    head.next.next.next.prev = head.next.next

    x = 8
    print(count_triplets(head, x))
C#
// C# implementation to count triplets in a sorted doubly
// linked list whose sum is equal to a given value 'x'
using System;
using System.Collections.Generic;

class Node {
    public int Data;
    public Node Next;
    public Node Prev;

    public Node(int val) {
        Data = val;
        Next = null;
        Prev = null;
    }
}

class GfG {

    // function to count triplets in a sorted doubly linked
    // list whose sum is equal to a given value 'x'
    static int CountTriplets(Node head, int x) {
        Node ptr1, ptr2;
        int count = 0;

        // Dictionary implemented as hash table
        Dictionary<int, Node> map
            = new Dictionary<int, Node>();

        // insert the <node data, node pointer> tuple in map
        for (Node ptr = head; ptr != null; ptr = ptr.Next)
            map[ptr.Data] = ptr;

        // generate all possible pairs
        for (ptr1 = head; ptr1 != null; ptr1 = ptr1.Next)
            for (ptr2 = ptr1.Next; ptr2 != null;
                 ptr2 = ptr2.Next) {

                // pSsum - sum of elements in the current
                // pair
                int pSum = ptr1.Data + ptr2.Data;

                // if 'x-pSsum' is present in 'map' and
                // either of the two nodes are not equal to
                // the 'map[x-pSsum]' node
                if (map.ContainsKey(x - pSum)
                    && map[x - pSum] != ptr1
                    && map[x - pSum] != ptr2)

                    // increment count
                    count++;
            }

        // required count of triplets
        // division by 3 as each triplet is counted 3 times
        return (count / 3);
    }

    static void Main() {

        // Create a hard-coded doubly linked list:
        // 1 <-> 2 <-> 3 <-> 4
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Prev = head;
        head.Next.Next = new Node(3);
        head.Next.Next.Prev = head.Next;
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Prev = head.Next.Next;

        int x = 8;
        Console.WriteLine(CountTriplets(head, x));
    }
}
JavaScript
// JavaScript implementation to count triplets in a
// sorted doubly linked list
// whose sum is equal to a given value 'x'

class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
        this.prev = null;
    }
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
function countTriplets(head, x) {
    let ptr1, ptr2;
    let count = 0;

    // Map implemented as an object to serve as hash table
    let map = {};

    // insert the <node data, node pointer> tuple in map
    for (let ptr = head; ptr !== null; ptr = ptr.next)
        map[ptr.data] = ptr;

    // generate all possible pairs
    for (ptr1 = head; ptr1 !== null; ptr1 = ptr1.next)
        for (ptr2 = ptr1.next; ptr2 !== null;
             ptr2 = ptr2.next) {

            // p_sum - sum of elements in the current pair
            let pSum = ptr1.data + ptr2.data;

            // if 'x-p_sum' is present in 'map' and either
            // of the two nodes are not equal to the
            // 'map[x-p_sum]' node
            if (map[x - pSum] !== undefined
                && map[x - pSum] !== ptr1
                && map[x - pSum] !== ptr2)

                // increment count
                count++;
        }

    // required count of triplets
    // division by 3 as each triplet is counted 3 times
    return (count / 3);
}

// Create a hard-coded doubly linked list:
// 1 <-> 2 <-> 3 <-> 4
const head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(4);
head.next.next.next.prev = head.next.next;

let x = 8;
console.log(countTriplets(head, x));

Output
1

[Expected Approach] Using two pointers – O(n^2) Time and O(1) Space

The idea is to create two pointers for each node: start: pointer next to current pointer, and last: pointer to last node in list.Then, count the number of pairs that sum up to value (x – curr->data). Algorithm described in Find pairs with given sum in doubly linked list post.

While start is not equal to last, there are three possibilites.

  • If sum = x – curr->data,increment the result, and set start = start->next and last = last->prev.
  • If sum < x – curr->data, then set start = start->next.
  • If sum > x – curr->data, then set last = last->prev
C++
// C++ implementation to count triplets in a sorted
// doubly linked list whose sum is equal to a
// given value 'x'
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *next, *prev;

    Node(int val) {
        data = val;
        next = nullptr;
        prev = nullptr;
    }
};


// function to count pairs whose sum equal to given 'value'
int countPairs(Node *start, Node *last, int value) {
    int count = 0;

    // The loop terminates when either of two pointers
    // become NULL, or they cross each other (last->next
    // == start), or they become same (start == last)
    while (start != nullptr && last != nullptr && 
           start != last && last->next != start) {

        // pair found
        if ((start->data + last->data) == value) {

            // increment count
            count++;

            // move start in forward direction
            start = start->next;

            // move last in backward direction
            last = last->prev;
        }

        // if sum is greater than 'value'
        // move last in backward direction
        else if ((start->data + last->data) > value)
            last = last->prev;

        // else move start in forward direction
        else
            start = start->next;
    }

    // required count of pairs
    return count;
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(Node *head, int x)  {

    // if list is empty
    if (head == nullptr)
        return 0;

    Node *curr, *first, *last;
    int count = 0;

    // get pointer to the last node of
    // the doubly linked list
    last = head;
    while (last->next != nullptr)
        last = last->next;

    // traversing the doubly linked list
    for (curr = head; curr != nullptr; curr = curr->next) {

        // for each curr node
        first = curr->next;

        // count pairs with sum(x - curr->data) in the range
        // first to last and add it to the 'count' of triplets
        count += countPairs(first, last, x - curr->data);
    }

    // required count of triplets
    return count;
}

int main() {

     // Create a hard-coded doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->prev = head;
    head->next->next = new Node(3);
    head->next->next->prev = head->next;
    head->next->next->next = new Node(4);
    head->next->next->next->prev = head->next->next;

    int x = 8;
    cout << countTriplets(head, x);

    return 0;
}
C
// C program to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
    struct Node *prev;
};

// function to count pairs whose sum equal to given 'value'
int countPairs(struct Node *start, struct Node *last, int value) {
    int count = 0;

    // The loop terminates when either of two pointers
    // become NULL, or they cross each other (last->next
    // == start), or they become same (start == last)
    while (start != NULL && last != NULL && 
           start != last && last->next != start) {

        // pair found
        if ((start->data + last->data) == value) {

            // increment count
            count++;

            // move start in forward direction
            start = start->next;

            // move last in backward direction
            last = last->prev;
        }

        // if sum is greater than 'value'
        // move last in backward direction
        else if ((start->data + last->data) > value)
            last = last->prev;

        // else move start in forward direction
        else
            start = start->next;
    }

    // required count of pairs
    return count;
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node *head, int x) {

    // if list is empty
    if (head == NULL)
        return 0;

    struct Node *curr;
    struct Node *first;
    struct Node *last;
    int count = 0;

    // get pointer to the last node of
    // the doubly linked list
    last = head;
    while (last->next != NULL)
        last = last->next;

    // traversing the doubly linked list
    for (curr = head; curr != NULL; curr = curr->next) {

        // for each curr node
        first = curr->next;

        // count pairs with sum(x - curr->data) in the range
        // first to last and add it to the 'count' of triplets
        count += countPairs(first, last, x - curr->data);
    }

    // required count of triplets
    return count;
}

struct Node *createNode(int new_data) { 
    struct Node *new_node = 
      (struct Node *)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    new_node->prev = NULL;
    return new_node;
}

int main() {

     // Create a hrad-coded doubly linked list:
    // 1 <-> 2 <-> 3 <-> 4
    struct Node *head = createNode(1);
    head->next = createNode(2);
    head->next->prev = head;
    head->next->next = createNode(3);
    head->next->next->prev = head->next;
    head->next->next->next = createNode(4);
    head->next->next->next->prev = head->next->next;

    int x = 8;
    printf("%d\n", countTriplets(head, x));

    return 0;
}
Java
// Java implementation to count triplets in a sorted doubly
// linked list whose sum is equal to a given value 'x'

class Node {
    int data;
    Node next, prev;

    Node(int d) {
        data = d;
        next = prev = null;
    }
}

class GfG {

    // function to count pairs whose sum equals to given
    // 'value'
    static int countPairs(Node start, Node last, int value) {
        int count = 0;

        // The loop terminates when either of two pointers
        // become NULL, or they cross each other (last.next
        // == start), or they become same (start == last)
        while (start != null && last != null
               && start != last && last.next != start) {

            // pair found
            if ((start.data + last.data) == value) {

                // increment count
                count++;

                // move start in forward direction
                start = start.next;

                // move last in backward direction
                last = last.prev;
            }

            // if sum is greater than 'value'
            // move last in backward direction
            else if ((start.data + last.data) > value)
                last = last.prev;

            // else move start in forward direction
            else
                start = start.next;
        }

        // required count of pairs
        return count;
    }

    // function to count triplets in a sorted doubly linked
    // list whose sum is equal to a given value 'x'
    static int countTriplets(Node head, int x) {

        // if list is empty
        if (head == null)
            return 0;

        Node curr, first, last;
        int count = 0;

        // get pointer to the last node of
        // the doubly linked list
        last = head;
        while (last.next != null)
            last = last.next;

        // traversing the doubly linked list
        for (curr = head; curr != null; curr = curr.next) {

            // for each curr node
            first = curr.next;

            // count pairs with sum(x - curr.data) in the
            // range first to last and add it to the 'count'
            // of triplets
            count += countPairs(first, last, x - curr.data);
        }

        // required count of triplets
        return count;
    }

    public static void main(String[] args) {

        // Manually create a doubly linked list:
        // 1 <-> 2 <-> 3 <-> 4
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.prev = head;
        head.next.next = new Node(3);
        head.next.next.prev = head.next;
        head.next.next.next = new Node(4);
        head.next.next.next.prev = head.next.next;

        int x = 8;
        System.out.println(countTriplets(head, x));
    }
}
Python
# Python implementation to count triplets in a sorted
# doubly linked list whose sum is equal to
# a given value 'x'

class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None

# function to count pairs whose sum 
# equal to given 'value'

def count_pairs(start, last, value):
    count = 0

    # The loop terminates when either of two pointers
    # become None, or they cross each other (last.next
    # == start), or they become same (start == last)
    while start is not None and last is not None and \
            start != last and last.next != start:

        # pair found
        if (start.data + last.data) == value:

            # increment count
            count += 1

            # move start in forward direction
            start = start.next

            # move last in backward direction
            last = last.prev

        # if sum is greater than 'value'
        # move last in backward direction
        elif (start.data + last.data) > value:
            last = last.prev

        # else move start in forward direction
        else:
            start = start.next

    # required count of pairs
    return count

# function to count triplets in a sorted doubly linked list
# whose sum is equal to a given value 'x'

def count_triplets(head, x):

    # if list is empty
    if head is None:
        return 0

    count = 0

    # get pointer to the last node of
    # the doubly linked list
    last = head
    while last.next is not None:
        last = last.next

    # traversing the doubly linked list
    curr = head
    while curr is not None:

        # for each curr node
        first = curr.next

        # count pairs with sum(x - curr.data) in the range
        # first to last and add it to the 'count' of triplets
        count += count_pairs(first, last, x - curr.data)

        # move to the next node
        curr = curr.next

    # required count of triplets
    return count

if __name__ == "__main__":

    # Create a hard-coded doubly linked list:
    # 1 <-> 2 <-> 3 <-> 4
    head = Node(1)
    head.next = Node(2)
    head.next.prev = head
    head.next.next = Node(3)
    head.next.next.prev = head.next
    head.next.next.next = Node(4)
    head.next.next.next.prev = head.next.next

    x = 8
    print(count_triplets(head, x))
C#
// C# implementation to count triplets in a sorted doubly
// linked list whose sum is equal to a given value 'x'
using System;

class Node {
    public int Data;
    public Node Next, Prev;

    public Node(int newData, Node prevNode) {
        Data = newData;
        Prev = prevNode;
        Next = null;
    }
}

class GfG {

    // function to count pairs whose sum equals the given value
    static int CountPairs(Node start, Node last, int value) {
        int count = 0;

        // The loop terminates when either of two pointers
        // become NULL, or they cross each other (last->next
        // == start), or they become same (start == last)
        while (start != null && last != null && start != last && start != last.Next) {

            // pair found
            if ((start.Data + last.Data) == value) {

                // increment count
                count++;

                // move start in forward direction
                start = start.Next;

                // move last in backward direction
                last = last.Prev;
            }

            // if sum is greater than 'value'
            // move last in backward direction
            else if ((start.Data + last.Data) > value)
                last = last.Prev;

            // else move start in forward direction
            else
                start = start.Next;
        }

        // required count of pairs
        return count;
    }

    // function to count triplets in a sorted doubly linked list
    // whose sum is equal to a given value 'x'
    static int CountTriplets(Node head, int x) {

        // if list is empty
        if (head == null)
            return 0;

        Node curr, first, last;
        int count = 0;

        // get pointer to the last node of
        // the doubly linked list
        last = head;
        while (last.Next != null)
            last = last.Next;

        // traversing the doubly linked list
        for (curr = head; curr != null; curr = curr.Next) {

            // for each curr node
            first = curr.Next;

            // count pairs with sum(x - curr.Data) in the
            // range first to last and add it to the 'count'
            // of triplets
            count += CountPairs(first, last, x - curr.Data);
        }

        // required count of triplets
        return count;
    }

    static void Main() {

        // Create a hard-coded doubly linked list:
        // 1 <-> 2 <-> 3 <-> 4
        Node head = new Node(1, null);
        head.Next = new Node(2, head);
        head.Next.Next = new Node(3, head.Next);
        head.Next.Next.Next = new Node(4, head.Next.Next);

        int x = 8;
        Console.WriteLine(CountTriplets(head, x));
    }
}
JavaScript
// JavaScript implementation to count triplets in a sorted
// doubly linked list whose sum is equal to a given value
// 'x'

class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
        this.prev = null;
    }
}

// function to count pairs whose sum equal to given 'value'
function countPairs(start, last, value) {
    let count = 0;

    // The loop terminates when either of two pointers
    // become null, or they cross each other (last.next
    // == start), or they become same (start == last)
    while (start !== null && last !== null && start !== last
           && last.next !== start) {

        // pair found
        if ((start.data + last.data) === value) {

            // increment count
            count++;

            // move start in forward direction
            start = start.next;

            // move last in backward direction
            last = last.prev;
        }

        // if sum is greater than 'value'
        // move last in backward direction
        else if ((start.data + last.data) > value)
            last = last.prev;

        // else move start in forward direction
        else
            start = start.next;
    }

    // required count of pairs
    return count;
}

// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
function countTriplets(head, x) {

    // if list is empty
    if (head === null)
        return 0;

    let curr, first, last;
    let count = 0;

    // get pointer to the last node of
    // the doubly linked list
    last = head;
    while (last.next !== null)
        last = last.next;

    // traversing the doubly linked list
    for (curr = head; curr !== null; curr = curr.next) {

        // for each curr node
        first = curr.next;

        // count pairs with sum(x - curr.data) in the range
        // first to last and add it to the 'count' of
        // triplets
        count += countPairs(first, last, x - curr.data);
    }

    // required count of triplets
    return count;
}

// Create a hard-coded doubly linked list:
// 1 <-> 2 <-> 3 <-> 4
const head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(4);
head.next.next.next.prev = head.next.next;

let x = 8;
console.log(countTriplets(head, x));

Output
1


Next Article
Practice Tags :

Similar Reads