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 −

  • curr := head, nxt := head

  • 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

    • display "Not found"

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
def insert(head, data):
   node = ListNode(0)
   node.data = data
   node.next = node.prev = None
   if (head == None):
      (head) = node
   else :
      node.next = head
      head.prev = node
      head = node
   return head
def get_pair_prod(head, x):
   curr = head
   nxt = head
   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):
      print( "Not found")
head = None
head = insert(head, 9)
head = insert(head, 8)
head = insert(head, 6)
head = insert(head, 5)
head = insert(head, 4)
head = insert(head, 2)
head = insert(head, 1)
x = 8
get_pair_prod(head, x)

Input

head = None
head = insert(head, 9)
head = insert(head, 8)
head = insert(head, 6)
head = insert(head, 5)
head = insert(head, 4)
head = insert(head, 2)
head = insert(head, 1)
x = 8

Output

( 1 , 8 )
( 2 , 4 )
raja
Published on 25-Aug-2020 11:55:31
Advertisements