Open In App

Find the Pair of Nodes with the Smallest Product in a Doubly Linked List

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a doubly linked list, the task is to find the pair of nodes whose product is the smallest among all possible pairs. Each node in the list contains an integer value, and you need to find the two nodes whose multiplication results in the minimum product.

Examples:

Input: 4 <-> 6 <-> 3 <-> 1 <-> 2 -> NULL
Output: 1 and 2
Explanation: The pair (1, 2) has the smallest product, which is 1 * 2 = 2.

Input: 5 <-> 2 <-> 1 <-> 1 <-> 3 <-> 4 -> NULL
Output: 1 and 1
Explanation: The pair (1, 1) has the smallest product, which is 1 * 1 = 1.

Approach: To solve the problem follow the below idea:

The problem is to find the pair of nodes in a doubly linked list with the smallest product. To achieve this, we iterate through the list, keeping track of the minimum product and the corresponding pair of nodes. We start with a large initial minimum product value and then compare the product of each pair of nodes. If we find a smaller product, we update our minimum product and record the current pair. This way, we guarantee that we find the pair with the smallest product by the end of the iteration.

Steps of the approach:

  • Initialize minProduct to a large value and firstNode and secondNode to NULL to store the pair with the minimum product.
  • Traverse the doubly linked list from the beginning to the end.
  • For each node, iterate through the remaining nodes in the list.
  • Calculate the product of the current node’s value with the value of each subsequent node.
  • Compare the calculated product with the current minimum product.
  • If the calculated product is smaller, update minProduct, firstNode, and secondNode accordingly.
  • Continue this process for all nodes in the list, considering all possible pairs.
  • Once the iteration is complete, firstNode and secondNode will contain the nodes with the smallest product, and minProduct will store the minimum product value.

Below is the code for the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Doubly linked list node structure
struct Node {
    int data;
    Node* next;
    Node* prev;
    Node(int val)
        : data(val)
        , next(NULL)
        , prev(NULL)
    {
    }
};
 
// Function to find the pair of nodes
// with the smallest product
pair<int, int> findSmallestProductPair(Node* head)
{
 
    // Initialize the minimum
    // product to a large value
    int minProduct = INT_MAX;
 
    // Initialize pointers to track the nodes
    // with the smallest product
    Node* firstNode = NULL;
    Node* secondNode = NULL;
 
    // Start iterating from the head
    // of the linked list
    Node* current = head;
 
    // Create a temporary pointer
    // to iterate through the
    // remaining nodes
    while (current) {
        Node* temp = current->next;
 
        // Calculate the product of
        // current node and temp
        // node
        while (temp) {
            int product = current->data * temp->data;
 
            // Update the minimum product
            // and the corresponding
            // nodes if needed
            if (product < minProduct) {
                minProduct = product;
                firstNode = current;
                secondNode = temp;
            }
 
            // Move to the next node
            temp = temp->next;
        }
 
        // Move to the next node
        // for the outer loop
        current = current->next;
    }
 
    // Return the pair with the
    // smallest product
    return make_pair(firstNode->data, secondNode->data);
}
 
// Function to display the
// doubly linked list
void displayList(Node* head)
{
    Node* current = head;
    while (current) {
        cout << current->data;
 
        // Print a separator between
        // nodes
        if (current->next) {
            cout << " <-> ";
        }
        current = current->next;
    }
 
    // Print "NULL" at the end to signify
    // the end of the list
    cout << " -> NULL" << endl;
}
 
// Drivers code
int main()
{
 
    // Create a doubly linked
    // list for testing
    Node* head = new Node(4);
    head->next = new Node(6);
    head->next->prev = head;
    head->next->next = new Node(3);
    head->next->next->prev = head->next;
    head->next->next->next = new Node(1);
    head->next->next->next->prev = head->next->next;
    head->next->next->next->next = new Node(2);
    head->next->next->next->next->prev
        = head->next->next->next;
 
    // Find and display the pair with
    // the smallest product
    pair<int, int> result = findSmallestProductPair(head);
    cout << "Output: " << result.first << " and "
         << result.second << endl;
 
    return 0;
}


Java




class Node {
    int data;
    Node next;
    Node prev;
 
    Node(int val) {
        data = val;
        next = null;
        prev = null;
    }
}
 
public class Main {
    // Function to find the pair of nodes with the smallest product
    static int[] findSmallestProductPair(Node head) {
        // Initialize the minimum product to a large value
        int minProduct = Integer.MAX_VALUE;
 
        // Initialize pointers to track the nodes with the smallest product
        Node firstNode = null;
        Node secondNode = null;
 
        // Start iterating from the head of the linked list
        Node current = head;
 
        // Iterate through the remaining nodes
        while (current != null) {
            Node temp = current.next; // Create a temporary pointer to iterate through the remaining nodes
 
            // Calculate the product of the current node and temp node
            while (temp != null) {
                int product = current.data * temp.data;
 
                // Update the minimum product and the corresponding nodes if needed
                if (product < minProduct) {
                    minProduct = product;
                    firstNode = current;
                    secondNode = temp;
                }
 
                // Move to the next node
                temp = temp.next;
            }
 
            // Move to the next node for the outer loop
            current = current.next;
        }
 
        // Return the pair with the smallest product
        return new int[]{firstNode.data, secondNode.data};
    }
 
    // Function to display the doubly linked list
    static void displayList(Node head) {
        Node current = head;
        while (current != null) {
            System.out.print(current.data);
 
            // Print a separator between nodes
            if (current.next != null) {
                System.out.print(" <-> ");
            }
            current = current.next;
        }
 
        // Print "None" at the end to signify the end of the list
        System.out.println(" -> NULL");
    }
 
    public static void main(String[] args) {
        // Create a doubly linked list for testing
        Node head = new Node(4);
        head.next = new Node(6);
        head.next.prev = head;
        head.next.next = new Node(3);
        head.next.next.prev = head.next;
        head.next.next.next = new Node(1);
        head.next.next.next.prev = head.next.next;
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.prev = head.next.next.next;
 
        // Find and display the pair with the smallest product
        int[] result = findSmallestProductPair(head);
        System.out.println("Output: " + result[0] + " and " + result[1]);
    }
}


Python3




# Python code for finding the pair of nodes with the smallest product
 
# Doubly linked list node structure
class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None
 
# Function to find the pair of nodes with the smallest product
def find_smallest_product_pair(head):
    # Initialize the minimum product to a large value
    min_product = float('inf')
 
    # Initialize pointers to track the nodes with the smallest product
    first_node = None
    second_node = None
 
    # Start iterating from the head of the linked list
    current = head
 
    # Iterate through the remaining nodes
    while current:
        temp = current.next  # Create a temporary pointer to iterate through the remaining nodes
 
        # Calculate the product of the current node and temp node
        while temp:
            product = current.data * temp.data
 
            # Update the minimum product and the corresponding nodes if needed
            if product < min_product:
                min_product = product
                first_node = current
                second_node = temp
 
            # Move to the next node
            temp = temp.next
 
        # Move to the next node for the outer loop
        current = current.next
 
    # Return the pair with the smallest product
    return (first_node.data, second_node.data)
 
# Function to display the doubly linked list
def display_list(head):
    current = head
    while current:
        print(current.data, end="")
 
        # Print a separator between nodes
        if current.next:
            print(" <-> ", end="")
        current = current.next
 
    # Print "None" at the end to signify the end of the list
    print(" -> None")
 
# Drivers code
if __name__ == "__main__":
    # Create a doubly linked list for testing
    head = Node(4)
    head.next = Node(6)
    head.next.prev = head
    head.next.next = Node(3)
    head.next.next.prev = head.next
    head.next.next.next = Node(1)
    head.next.next.next.prev = head.next.next
    head.next.next.next.next = Node(2)
    head.next.next.next.next.prev = head.next.next.next
 
    # Find and display the pair with the smallest product
    result = find_smallest_product_pair(head)
    print("Output:", result[0], "and", result[1])


C#




using System;
 
// Doubly linked list node structure
public class Node
{
    public int data;
    public Node next;
    public Node prev;
 
    public Node(int val)
    {
        data = val;
        next = null;
        prev = null;
    }
}
 
class Program
{
    // Function to find the pair of nodes with the smallest product
    static Tuple<int, int> FindSmallestProductPair(Node head)
    {
        // Initialize the minimum product to a large value
        int minProduct = int.MaxValue;
 
        // Initialize pointers to track the nodes with the smallest product
        Node firstNode = null;
        Node secondNode = null;
 
        // Start iterating from the head of the linked list
        Node current = head;
 
        // Create a temporary pointer to iterate through the remaining nodes
        while (current != null)
        {
            Node temp = current.next;
 
            // Calculate the product of current node and temp node
            while (temp != null)
            {
                int product = current.data * temp.data;
 
                // Update the minimum product and the corresponding nodes if needed
                if (product < minProduct)
                {
                    minProduct = product;
                    firstNode = current;
                    secondNode = temp;
                }
 
                // Move to the next node
                temp = temp.next;
            }
 
            // Move to the next node for the outer loop
            current = current.next;
        }
 
        // Return the pair with the smallest product
        return Tuple.Create(firstNode.data, secondNode.data);
    }
 
    // Function to display the doubly linked list
    static void DisplayList(Node head)
    {
        Node current = head;
        while (current != null)
        {
            Console.Write(current.data);
 
            // Print a separator between nodes
            if (current.next != null)
            {
                Console.Write(" <-> ");
            }
            current = current.next;
        }
 
        // Print "NULL" at the end to signify the end of the list
        Console.WriteLine(" -> NULL");
    }
 
    // Main method
    static void Main()
    {
        // Create a doubly linked list for testing
        Node head = new Node(4);
        head.next = new Node(6);
        head.next.prev = head;
        head.next.next = new Node(3);
        head.next.next.prev = head.next;
        head.next.next.next = new Node(1);
        head.next.next.next.prev = head.next.next;
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.prev = head.next.next.next;
 
        // Find and display the pair with the smallest product
        Tuple<int, int> result = FindSmallestProductPair(head);
        Console.WriteLine("Output: " + result.Item1 + " and " + result.Item2);
    }
}


Javascript




// Doubly linked list node structure
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
        this.prev = null;
    }
}
 
// Function to find the pair of nodes with the smallest product
function findSmallestProductPair(head) {
    // Initialize the minimum product to a large value
    let minProduct = Infinity;
 
    // Initialize pointers to track the nodes with the smallest product
    let firstNode = null;
    let secondNode = null;
 
    // Start iterating from the head of the linked list
    let current = head;
 
    // Create a temporary pointer to iterate through the remaining nodes
    while (current) {
        let temp = current.next;
 
        // Calculate the product of current node and temp node
        while (temp) {
            let product = current.data * temp.data;
 
            // Update the minimum product and the corresponding nodes if needed
            if (product < minProduct) {
                minProduct = product;
                firstNode = current;
                secondNode = temp;
            }
 
            // Move to the next node
            temp = temp.next;
        }
 
        // Move to the next node for the outer loop
        current = current.next;
    }
 
    // Return the pair with the smallest product
    return [firstNode.data, secondNode.data];
}
 
// Function to display the doubly linked list
function displayList(head) {
    let current = head;
    while (current) {
        console.log(current.data);
 
        // Print a separator between nodes
        if (current.next) {
            console.log(" <-> ");
        }
        current = current.next;
    }
 
    // Print "NULL" at the end to signify the end of the list
    console.log(" -> NULL");
}
 
// Drivers code
function main() {
    // Create a doubly linked list for testing
    let head = new Node(4);
    head.next = new Node(6);
    head.next.prev = head;
    head.next.next = new Node(3);
    head.next.next.prev = head.next;
    head.next.next.next = new Node(1);
    head.next.next.next.prev = head.next.next;
    head.next.next.next.next = new Node(2);
    head.next.next.next.next.prev = head.next.next.next;
 
    // Find and display the pair with the smallest product
    let result = findSmallestProductPair(head);
    console.log("Output: " + result[0] + " and " + result[1]);
}
 
// Run the main function
main();


Output

Output: 1 and 2








Time Complexity: O(n), where n is the number of nodes in the doubly linked list.
Auxiliary Space: O(1) because we use a constant amount of extra space.



Similar Reads

Product of all prime nodes in a Doubly Linked List
Given a doubly linked list containing N nodes. The task is to find the product of all prime nodes. Example: Input: List = 15 &lt;=&gt; 16 &lt;=&gt; 6 &lt;=&gt; 7 &lt;=&gt; 17 Output: Product of Prime Nodes: 119 Input: List = 5 &lt;=&gt; 3 &lt;=&gt; 4 &lt;=&gt; 2 &lt;=&gt; 9 Output: Product of Prime Nodes: 30 Approach: Initialize a pointer temp with
10 min read
Product of all nodes in a doubly linked list divisible by a given number K
Given a doubly-linked list containing N nodes and given a number K. The task is to find the product of all such nodes which are divisible by K. Examples: Input : List = 15 &lt;=&gt; 16 &lt;=&gt; 10 &lt;=&gt; 9 &lt;=&gt; 6 &lt;=&gt; 7 &lt;=&gt; 17 K = 3 Output : Product = 810 Input : List = 5 &lt;=&gt; 3 &lt;=&gt; 6 &lt;=&gt; 8 &lt;=&gt; 4 &lt;=&gt;
9 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node. Introduction to Doubly linked list : A Doubly Linked List (D
2 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
19 min read
Find pairs with given product in a sorted Doubly Linked List
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. Examples: Input : List = 1 &lt;=&gt; 2 &lt;=&gt; 4 &lt;=&gt; 5 &lt;=&gt; 6 &lt;=&gt; 8 &lt;=&gt; 9 x = 8 Output: (1, 8), (2, 4) Input : List = 1 &lt;=&gt; 2 &lt;
10 min read
Count of quadruples with product of a pair equal to the product of the remaining pair
Given an array arr[] of size N, the task is to count the number of unique quadruples (a, b, c, d) from the array such that the product of any pair of elements of the quadruple is equal to the product of the remaining pair of elements. Examples: Input: arr[] = {2, 3, 4, 6}Output: 8Explanation:There are 8 quadruples in the array, i.e. (2, 6, 3, 4), (
7 min read
Reverse a Doubly Linked List without swapping nodes
Write a program to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (or start) and then changing the head pointer in the
10 min read