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

Given a sorted doubly linked list of distinct nodes(no two nodes have the same data) and a value x. The task is to count the triplets in the list that product up to a given value x.

Examples:

Input: list = 1->2->4->5->6->8->9, x = 8
Output:
Triplet is (1, 2, 4)

Input: list = 1->2->4->5->6->8->9, x = 120
Output:
Triplet is (4, 5, 6)

Naive Approach: Using three nested loops generate all triplets and check whether elements in the triplet product up to x or not.

Below is the implementation of the above approach:

## Javascript



Output:

Count = 1

Complexity Analysis:

• Time Complexity: O(n^3)
• Auxiliary Space: O(1)

Method-2 (Hashing):

Create a hash table with (key, value) tuples represented as (node data, node pointer) tuples. Traverse the doubly linked list and store each nodeâ€™s data and its pointer pair(tuple) in the hash table. Now, generate each possible pair of nodes. For each pair of nodes, calculate the p_product(product of data in the two nodes) and check whether (x/p_product) exists in the hash table or not.

If it exists, then also verify that the two nodes in the pair are not same as to the node associated with (x/p_product) in the hash table and finally increment count. Return (count / 3) as each triplet is counted 3 times in the above process.

Below is the implementation of the above approach:

## Javascript



Output:

Count = 1

Complexity Analysis:

• Time Complexity: O(n^2)
• Auxiliary Space: O(n)

Method-3 (Use of two pointers):

Traverse the doubly linked list from left to right. For each current node during the traversal, initialize two pointers first = pointer to the node next to the current node and last = pointer to the last node of the list. Now, count pairs in the list from first to the last pointer that product up to the value (x / current nodeâ€™s data) (algorithm described in this post). Add this count to the total_count of triplets. Pointer to the last node can be found only once in the beginning.

Below is the implementation of the above approach:

## Javascript



Output:

Count = 1

Complexity Analysis:

• Time Complexity: O(n^2)
• Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!