VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-triplets-sorted-doubly-linked-list-whose-sum-equal-given-value-x/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 13 Apr, 2023

Given a sorted doubly linked list of distinct nodes(no two nodes have the same data) and a value x. Count triplets in the list that sum up to a given value x.

Examples:
 

👁 Image

Method 1 (Naive Approach): 
Using three nested loops generate all triplets and check whether elements in the triplet sum up to x or not.

👁 Complete Interview Preparation - GFG
 


Output
Count = 2

Output: 

Count = 2


Time Complexity: O(n3
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_sum(sum of data in the two nodes) and check whether (x-p_sum) exists in the hash table or not. If it exists, then also verify that the two nodes in the pair are not same to the node associated with (x-p_sum) in the hash table and finally increment count. Return (count / 3) as each triplet is counted 3 times in the above process.


Output
Count = 2

Output: 

Count = 2


Time Complexity: O(n2
Auxiliary Space: O(n)

Method 3 Efficient Approach(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 last pointer that sum up to 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.


Output
Count = 2

Output: 

Count = 2


Time Complexity: O(n2
Auxiliary Space: O(1)


Another Solution  

find tripple sum in Doubly linkedList.


Output
1, 5, 9
1, 6, 8
2, 4, 9
2, 5, 8
4, 5, 6
Time complexity : O(n^2), where n is the length of the linked list. 
Space complexity :O(1),because it only uses a constant amount of extra memory to store pointers to the nodes being examined


 

Comment
Article Tags: