Check if a pair with given product exists in Linked list

Given a linked list, and a product K. The task is to check if there exist two numbers in the linked list whose product is equal to given number K. If there exist two numbers, print them. If there are multiple answers, print any of them.

Examples:

Input : List  = 1 -> 2 -> 3 -> 4 -> 5 -> NULL 
        K = 2
Output : Pair is (1, 2)

Input : List = 10 -> 12 -> 31 -> 42 -> 53 -> NULL 
        K = 15
Output : No Pair Exists

Method 1 (Brute force): Run two nested loops to generate all possible pairs of the linked list and check if the product of any pair matches with the given product K.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP code to find the pair with given product
#include <bits/stdc++.h>
using namespace std;
  
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
  
/* Given a reference (pointer to pointer) 
    to the head of a list and an int, 
    push a new node on the front  
    of the list. */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
  
/* Takes head pointer of the linked list and product*/
int check_pair_product(struct Node* head, int prod)
{
    struct Node *p = head, *q;
    while (p != NULL) {
  
        q = p->next;
        while (q != NULL) {
  
            // check if both product is equal to
            // given product
            if ((p->data) * (q->data) == prod) {
                cout << p->data << " " << q->data;
                return true;
            }
            q = q->next;
        }
  
        p = p->next;
    }
  
    return 0;
}
  
/* Driver program to test above function */
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
  
    /* Use push() to construct linked list*/
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);
    push(&head, 18);
    push(&head, 47);
    push(&head, 16);
    push(&head, 12);
    push(&head, 14);
  
    /* function to print the result*/
    bool res = check_pair_product(head, 26);
    if (res == false)
        cout << "NO PAIR EXIST";
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to find the pair with 
# given product 
  
# Link list node
class Node: 
      
    def __init__(self, data, next):
        self.data = data
        self.next = next
          
class LinkedList:
      
    def __init__(self):
        self.head = None
      
    # Push a new node on the front of the list.     
    def push(self, new_data):
        new_node = Node(new_data, self.head)
        self.head = new_node
  
    # Takes head pointer of the linked 
    # list and product
    def check_pair_product(self, prod): 
      
        p = self.head
        while p != None
      
            q = p.next
            while q != None
      
                # Check if both product is equal 
                # to given product 
                if p.data * q.data == prod: 
                    print(p.data, q.data) 
                    return True
                  
                q = q.next
      
            p = p.next
              
        return False
  
# Driver Code
if __name__ == "__main__":
  
    # Start with the empty list
    linkedlist = LinkedList()
  
    # Use push() to construct linked list
    linkedlist.push(1
    linkedlist.push(4
    linkedlist.push(1
    linkedlist.push(12
    linkedlist.push(1
    linkedlist.push(18
    linkedlist.push(47
    linkedlist.push(16
    linkedlist.push(12
    linkedlist.push(14
  
    # function to print the result
    res = linkedlist.check_pair_product(26
    if res == False
        print("NO PAIR EXIST"
  
# This code is contributed by Rituraj Jain

chevron_right


Output:

NO PAIR EXIST

Time complexity: O(N2), where N is the length of the linked list.

Method 2 (using hashing):

  1. Take a hashtable and mark all element with zero.
  2. Iteratively mark all the element as 1 in hashtable which are present in linked list.
  3. Now, start traversing the linked list and check if the given product is divisible by current element of linked list, if yes then check if (K/current_element) of linked list is present in hashtable or not.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP code to find the pair with given product
#include <bits/stdc++.h>
#define MAX 100000
using namespace std;
  
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
  
/* Given a reference (pointer to pointer) 
    to the head of a list and an int, 
    push a new node on the front  
    of the list. */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
  
// Function to check if pair with the given product
// exists in the list
// Takes head pointer of the linked list and product
bool check_pair_product(struct Node* head, int prod)
{
    unordered_set<int> s;
  
    struct Node* p = head;
  
    while (p != NULL) {
  
        int curr = p->data;
  
        // Check if pair exits
        if ((prod % curr == 0) && (s.find(prod / curr) != s.end())) {
            cout << curr << " " << prod / curr;
            return true;
        }
  
        s.insert(p->data);
        p = p->next;
    }
  
    return false;
}
  
/* Driver program to test above function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
  
    /* Use push() to construct linked list */
    push(&head, 1);
    push(&head, 2);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);
    push(&head, 18);
    push(&head, 47);
    push(&head, 16);
    push(&head, 12);
    push(&head, 14);
  
    /* function to print the result*/
    bool res = check_pair_product(head, 24);
    if (res == false)
        cout << "NO PAIR EXIST";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to find the pair with given product
import java.util.*;
  
class Solution {
  
    static final int MAX = 100000;
  
    /* Link list node */
    static class Node {
        int data;
        Node next;
    }
  
    /* Given a reference (pointer to pointer)  
    to the head of a list and an int,  
    push a new node on the front   
    of the list. */
    static Node push(Node head_ref, int new_data)
    {
        Node new_node = new Node();
        new_node.data = new_data;
        new_node.next = (head_ref);
        (head_ref) = new_node;
        return head_ref;
    }
  
    // Function to check if pair with given product
    // exists in the list
    // Takes head pointer of the linked list and product
    static boolean check_pair_product(Node head, int prod)
    {
        Vector<Integer> s = new Vector<Integer>();
  
        Node p = head;
  
        while (p != null) {
  
            int curr = p.data;
  
            // Check if pair exits
            if ((prod % curr == 0) && (s.contains(prod / curr))) {
                System.out.print(curr + " " + (prod / curr));
                return true;
            }
  
            s.add(p.data);
            p = p.next;
        }
  
        return false;
    }
  
    /* Driver program to test above function*/
    public static void main(String args[])
    {
        /* Start with the empty list */
        Node head = null;
  
        /* Use push() to construct linked list */
        head = push(head, 1);
        head = push(head, 2);
        head = push(head, 1);
        head = push(head, 12);
        head = push(head, 1);
        head = push(head, 18);
        head = push(head, 47);
        head = push(head, 16);
        head = push(head, 12);
        head = push(head, 14);
  
        /* function to print the result*/
        boolean res = check_pair_product(head, 24);
        if (res == false)
            System.out.println("NO PAIR EXIST");
    }
}
  
// This code is contributed
// by Arnab Kundu

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to find the pair with
# given product 
  
# Link list node
class Node: 
      
    def __init__(self, data, next):
        self.data = data
        self.next = next
          
class LinkedList:
      
    def __init__(self):
        self.head = None
      
    # Push a new node on the front of the list.     
    def push(self, new_data):
        new_node = Node(new_data, self.head)
        self.head = new_node
  
    # Checks if pair with given product
    # exists in the list or not
    def check_pair_product(self, prod): 
      
        p = self.head
        s = set()
        while p != None
      
            curr = p.data 
  
            # Check if pair exits 
            if (prod % curr == 0 and
               (prod // curr) in s):
                print(curr, prod // curr) 
                return True
      
            s.add(p.data); 
            p = p.next;
              
        return False
  
# Driver Code
if __name__ == "__main__":
  
    # Start with the empty list
    linkedlist = LinkedList()
  
    # Use push() to construct linked list
    linkedlist.push(1
    linkedlist.push(2
    linkedlist.push(1
    linkedlist.push(12
    linkedlist.push(1
    linkedlist.push(18
    linkedlist.push(47
    linkedlist.push(16
    linkedlist.push(12
    linkedlist.push(14
  
    # function to print the result
    res = linkedlist.check_pair_product(24
    if res == False
        print("NO PAIR EXIST"
  
# This code is contributed by Rituraj Jain

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to find the pair with given product
using System;
using System.Collections.Generic;
  
class GFG {
  
    static readonly int MAX = 100000;
  
    /* Link list node */
    public class Node {
        public int data;
        public Node next;
    }
  
    /* Given a reference (pointer to pointer) 
    to the head of a list and an int, 
    push a new node on the front 
    of the list. */
    static Node push(Node head_ref, int new_data)
    {
        Node new_node = new Node();
        new_node.data = new_data;
        new_node.next = (head_ref);
        (head_ref) = new_node;
        return head_ref;
    }
  
    // Function to check if pair with given product
    // exists in the list
    // Takes head pointer of the linked list and product
    static bool check_pair_product(Node head, int prod)
    {
        List<int> s = new List<int>();
  
        Node p = head;
  
        while (p != null) {
  
            int curr = p.data;
  
            // Check if pair exits
            if ((prod % curr == 0) && (s.Contains(prod / curr))) {
                Console.Write(curr + " " + (prod / curr));
                return true;
            }
  
            s.Add(p.data);
            p = p.next;
        }
  
        return false;
    }
  
    /* Driver code*/
    public static void Main(String[] args)
    {
        /* Start with the empty list */
        Node head = null;
  
        /* Use push() to construct linked list */
        head = push(head, 1);
        head = push(head, 2);
        head = push(head, 1);
        head = push(head, 12);
        head = push(head, 1);
        head = push(head, 18);
        head = push(head, 47);
        head = push(head, 16);
        head = push(head, 12);
        head = push(head, 14);
  
        /* function to print the result*/
        bool res = check_pair_product(head, 24);
        if (res == false)
            Console.Write("NO PAIR EXIST");
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

2 12

Time complexity : O(N)
Auxiliary Space : O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.