Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in the doubly linked list whose product is equal to given value x, without using any extra space.
Input : List = 1 <=> 2 <=> 4 <=> 5 <=> 6 <=> 8 <=> 9 x = 8 Output: (1, 8), (2, 4) Input : List = 1 <=> 2 <=> 3 <=> 4 <=> 5 <=> 6 <=> 7 x = 6 Output: (1, 6), (2, 3)
A Simple Approach for this problem is to traverse the linked list using two nested loops and find all pairs and check for the pairs with product equals to x. Time complexity for this problem will be O(n^2), n is total number of nodes in doubly linked list.
An Efficient Solution for this problem is same as this article. Here is the algorithm :
- Initialize two pointer variables to find the candidate elements in the sorted doubly linked list. Initialize first with start of doubly linked list i.e; first=head and initialize second with last node of doubly linked list i.e; second=last_node.
- We initialize first and second pointers as first and last nodes. Here we don’t have random access, so to find second pointer, we traverse the list to initialize second.
- If current product of first and second is less than x, then we move first in forward direction. If current product of first and second element is greater than x, then we move second in backward direction.
- Loop termination conditions are also different from arrays. The loop terminates when either of two pointers become NULL, or they cross each other (second->next = first), or they become same (first == second)
Below is the implementation of the above approach:
(1, 8) (2, 4)
Time complexity : O(n)
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Find pairs with given sum in doubly linked list
- Insert value in sorted way in a sorted doubly linked list
- Sort a k sorted doubly linked list
- Product of all prime nodes in a Doubly Linked List
- Remove duplicates from a sorted doubly linked list
- Product of all nodes in a doubly linked list divisible by a given number K
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Sorted insert in a doubly linked list with head and tail pointers
- Find the largest node in Doubly linked list
- Program to find size of Doubly Linked List
- Sorted merge of two sorted doubly circular linked lists
- Find the product of first k nodes of the given Linked List
- Find the product of last N nodes of the given Linked List
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.