# Find pairs with given product in a sorted Doubly Linked List in Python

PythonServer Side ProgrammingProgramming

Suppose we have a sorted doubly linked list of unique positive numbers; we have to find pairs in the doubly linked list whose product is same as a given value x. We have to keep in mind that, this will be solved without consuming any extra space.

So, if the input is like L = 1 ⇔ 2 ⇔ 4 ⇔ 5 ⇔ 6 ⇔ 8 ⇔ 9 and x = 8, then the output will be (1, 8), (2, 4)

To solve this, we will follow these steps −

• while nxt.next is not None is non-zero, do

• nxt := nxt.next

• found := False

• while curr and nxt are not null and curr and nxt are different and nxt.next is not curr, do

• if (curr.data * nxt.data) is same as x, then

• found := True

• display a pair curr.data, nxt.data

• curr := curr.next

• nxt := nxt.prev

• otherwise,

• if (curr.data * nxt.data) < x, then

• curr := curr.next

• otherwise,

• nxt := nxt.prev

• if found is False, then

## Example

Let us see the following implementation to get better understanding −

Live Demo

class ListNode:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
node = ListNode(0)
node.data = data
node.next = node.prev = None
else :
while (nxt.next != None):
nxt = nxt.next
found = False
while (curr != None and nxt != None and curr != nxt and nxt.next != curr) :
if ((curr.data * nxt.data) == x) :
found = True
print("(", curr.data, ", ", nxt.data, ")")
curr = curr.next
nxt = nxt.prev
else :
if ((curr.data * nxt.data) < x):
curr = curr.next
else:
nxt = nxt.prev
if (found == False):
x = 8
get_pair_prod(head, x)

## Input

head = None
x = 8
( 1 , 8 )
( 2 , 4 )