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

Finding pairs with a given product in a sorted doubly linked list is an efficient algorithm that uses the two-pointer technique. Given a sorted doubly linked list of unique positive numbers, we need to find all pairs whose product equals a target value x, without using extra space.

For example, if we have a doubly linked list: 1 ? 2 ? 4 ? 5 ? 6 ? 8 ? 9 and target x = 8, the pairs would be (1, 8) and (2, 4).

Algorithm Steps

The solution uses two pointers starting from opposite ends of the list:

  • Initialize curr pointer at the head (smallest element)
  • Initialize nxt pointer at the tail (largest element)
  • Move pointers based on product comparison:
    • If product equals target: found a pair, move both pointers
    • If product is less than target: move curr forward
    • If product is greater than target: move nxt backward
  • Continue until pointers meet or cross each other

Implementation

class ListNode:
    def __init__(self, data):
        self.data = data
        self.prev = None
        self.next = None

def insert(head, data):
    node = ListNode(data)
    if head == None:
        head = node
    else:
        node.next = head
        head.prev = node
        head = node
    return head

def get_pair_prod(head, x):
    if head == None:
        print("Empty list")
        return
    
    # Set curr to head (smallest element)
    curr = head
    
    # Set nxt to tail (largest element)
    nxt = head
    while nxt.next != None:
        nxt = nxt.next
    
    found = False
    
    # Two pointer approach
    while (curr != None and nxt != None and curr != nxt and nxt.next != curr):
        product = curr.data * nxt.data
        
        if product == x:
            found = True
            print(f"({curr.data}, {nxt.data})")
            curr = curr.next
            nxt = nxt.prev
        elif product < x:
            curr = curr.next
        else:
            nxt = nxt.prev
    
    if not found:
        print("No pairs found")

# Create the doubly linked list: 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9
head = None
elements = [9, 8, 6, 5, 4, 2, 1]  # Insert in reverse order
for element in elements:
    head = insert(head, element)

x = 8
print(f"Pairs with product {x}:")
get_pair_prod(head, x)
Pairs with product 8:
(1, 8)
(2, 4)

How It Works

The algorithm leverages the sorted property of the doubly linked list:

  1. Two-pointer technique: Start with the smallest and largest elements
  2. Product comparison: Compare current product with target value
  3. Pointer movement: Move pointers inward based on comparison result
  4. Termination: Stop when pointers meet or cross each other

Time and Space Complexity

Aspect Complexity Explanation
Time O(n) Each node visited at most once
Space O(1) Only two pointers used

Example with Different Target

# Same doubly linked list, different target
x = 12
print(f"Pairs with product {x}:")
get_pair_prod(head, x)
Pairs with product 12:
(2, 6)

Conclusion

This algorithm efficiently finds pairs with a given product in O(n) time and O(1) space by using the two-pointer technique on a sorted doubly linked list. The key insight is leveraging the sorted property to move pointers intelligently based on product comparisons.

Updated on: 2026-03-25T09:49:42+05:30

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements