Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Two nodes in a Linked list whose product is equal to the target value
Next article icon

Count pairs from two linked lists whose product is equal to a given value

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements. Given a value X. The problem is to count all pairs from both lists whose product is equal to the given value x.

Note:The pair must have an element from each linked list.

Examples: 

Input : list1 = 3->1->5->7         list2 = 8->2->5->3         X = 10 Output : 1 The pair is: (5, 2)  Input : list1 = 4->3->5->7->11->2->1         list2 = 2->3->4->5->6->8-12         X = 9    Output : 1 The pair is: (3, 3)

A simple approach is using two loops pick elements from both the linked lists and check whether the product of the pair is equal to the given value X or not. Count all such pairs and print the result.

Below is the implementation of the above approach:  

C++




// C++ program to count all pairs from both the
// linked lists whose product is equal to
// a given value
 
#include <iostream>
using namespace std;
 
/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list to the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
// Function to count all pairs from both the linked lists
// whose product is equal to a given value
int countPairs(struct Node* head1, struct Node* head2, int x)
{
    int count = 0;
 
    struct Node *p1, *p2;
 
    // Traverse the 1st linked list
    for (p1 = head1; p1 != NULL; p1 = p1->next) {
        // for each node of 1st list
        // Traverse the 2nd list
        for (p2 = head2; p2 != NULL; p2 = p2->next) {
            // if sum of pair is equal to 'x'
            // increment count
            if ((p1->data * p2->data) == x)
                count++;
        }
    }
 
    // required count of pairs
    return count;
}
 
// Driver Code
int main()
{
    struct Node* head1 = NULL;
    struct Node* head2 = NULL;
 
    // create linked list1 3->1->5->7
    push(&head1, 7);
    push(&head1, 5);
    push(&head1, 1);
    push(&head1, 3);
 
    // create linked list2 8->2->5->3
    push(&head2, 3);
    push(&head2, 5);
    push(&head2, 2);
    push(&head2, 8);
 
    int x = 10;
 
    cout << "Count = " << countPairs(head1, head2, x);
 
    return 0;
}
 
 

Java




// Java program to count all pairs from both the
// linked lists whose product is equal to
// a given value
 
class GFG
{
 
    /* A Linked list node */
    static class Node
    {
        int data;
        Node next;
    };
 
    // function to insert a node at the
    // beginning of the linked list
    static Node push(Node head_ref, int new_data)
    {
        /* allocate node */
        Node new_node = new Node();
 
        /* put in the data */
        new_node.data = new_data;
 
        /* link the old list to the new node */
        new_node.next = head_ref;
 
        /* move the head to point to the new node */
        head_ref = new_node;
        return head_ref;
    }
 
    // Function to count all pairs from both the linked lists
    // whose product is equal to a given value
    static int countPairs(Node head1, Node head2, int x)
    {
        int count = 0;
 
        Node p1, p2;
 
        // Traverse the 1st linked list
        for (p1 = head1; p1 != null; p1 = p1.next)
        {
            // for each node of 1st list
            // Traverse the 2nd list
            for (p2 = head2; p2 != null; p2 = p2.next)
            {
                // if sum of pair is equal to 'x'
                // increment count
                if ((p1.data * p2.data) == x)
                {
                    count++;
                }
            }
        }
 
        // required count of pairs
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        Node head1 = null;
        Node head2 = null;
 
        // create linked list1 3.1.5.7
        head1 = push(head1, 7);
        head1 = push(head1, 5);
        head1 = push(head1, 1);
        head1 = push(head1, 3);
 
        // create linked list2 8.2.5.3
        head2 = push(head2, 3);
        head2 = push(head2, 5);
        head2 = push(head2, 2);
        head2 = push(head2, 8);
 
        int x = 10;
 
        System.out.print("Count = " + countPairs(head1, head2, x));
    }
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program to count all pairs from both the
# linked lists whose product is equal to
# a given value
  
''' A Linked list node '''
class Node:
     
    def __init__(self, data):
        self.data = data
        self.next = None
      
# function to insert a node at the
# beginning of the linked list
def push(head_ref, new_data):
 
    ''' allocate node '''
    new_node = Node(new_data)
  
    ''' put in the data '''
    new_node.data = new_data;
  
    ''' link the old list to the new node '''
    new_node.next = (head_ref);
  
    ''' move the head to point to the new node '''
    (head_ref) = new_node;
     
    return head_ref
  
# Function to count all pairs from both the linked lists
# whose product is equal to a given value
def countPairs(head1, head2, x):
    count = 0;   
    p1 = head1
     
    # Traverse the 1st linked list
    while p1 != None:       
        p2 = head2
         
        # for each node of 1st list
        # Traverse the 2nd list
        while p2 != None:       
         
            # if sum of pair is equal to 'x'
            # increment count
            if ((p1.data * p2.data) == x):
                count += 1
            p2 = p2.next
        p1 = p1.next
         
    # required count of pairs
    return count;
  
# Driver Code
if __name__=='__main__':
     
    head1 = None;
    head2 = None;
  
    # create linked list1 3.1.5.7
    head1 = push(head1, 7);
    head1 = push(head1, 5);
    head1 = push(head1, 1);
    head1 = push(head1, 3);
  
    # create linked list2 8.2.5.3
    head2 = push(head2, 3);
    head2 = push(head2, 5);
    head2 = push(head2, 2);
    head2 = push(head2, 8);
  
    x = 10;
  
    print("Count = " + str(countPairs(head1, head2, x)))
  
# This code is contributed by rutvik_56
 
 

C#




// C# program to count all pairs from both the
// linked lists whose product is equal to
// a given value
using System;
 
class GFG
{
 
    /* A Linked list node */
    class Node
    {
        public int data;
        public Node next;
    };
 
    // function to insert a node at the
    // beginning of the linked list
    static Node push(Node head_ref, int new_data)
    {
        /* allocate node */
        Node new_node = new Node();
 
        /* put in the data */
        new_node.data = new_data;
 
        /* link the old list to the new node */
        new_node.next = head_ref;
 
        /* move the head to point to the new node */
        head_ref = new_node;
        return head_ref;
    }
 
    // Function to count all pairs from both the linked lists
    // whose product is equal to a given value
    static int countPairs(Node head1, Node head2, int x)
    {
        int count = 0;
 
        Node p1, p2;
 
        // Traverse the 1st linked list
        for (p1 = head1; p1 != null; p1 = p1.next)
        {
            // for each node of 1st list
            // Traverse the 2nd list
            for (p2 = head2; p2 != null; p2 = p2.next)
            {
                // if sum of pair is equal to 'x'
                // increment count
                if ((p1.data * p2.data) == x)
                {
                    count++;
                }
            }
        }
 
        // required count of pairs
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        Node head1 = null;
        Node head2 = null;
 
        // create linked list1 3->1->5->7
        head1 = push(head1, 7);
        head1 = push(head1, 5);
        head1 = push(head1, 1);
        head1 = push(head1, 3);
 
        // create linked list2 8->2->5->3
        head2 = push(head2, 3);
        head2 = push(head2, 5);
        head2 = push(head2, 2);
        head2 = push(head2, 8);
 
        int x = 10;
 
        Console.Write("Count = " + countPairs(head1, head2, x));
    }
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
// javascript program to count all pairs from both the
// linked lists whose product is equal to
// a given value
    /* A Linked list node */
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
    // function to insert a node at the
    // beginning of the linked list
    function push(head_ref , new_data) {
        /* allocate node */
var new_node = new Node();
 
        /* put in the data */
        new_node.data = new_data;
 
        /* link the old list to the new node */
        new_node.next = head_ref;
 
        /* move the head to point to the new node */
        head_ref = new_node;
        return head_ref;
    }
 
    // Function to count all pairs from both the linked lists
    // whose product is equal to a given value
    function countPairs(head1,  head2 , x) {
        var count = 0;
 
var p1, p2;
 
        // Traverse the 1st linked list
        for (p1 = head1; p1 != null; p1 = p1.next) {
            // for each node of 1st list
            // Traverse the 2nd list
            for (p2 = head2; p2 != null; p2 = p2.next) {
                // if sum of pair is equal to 'x'
                // increment count
                if ((p1.data * p2.data) == x) {
                    count++;
                }
            }
        }
 
        // required count of pairs
        return count;
    }
 
    // Driver Code
     
var head1 = null;
var head2 = null;
 
        // create linked list1 3.1.5.7
        head1 = push(head1, 7);
        head1 = push(head1, 5);
        head1 = push(head1, 1);
        head1 = push(head1, 3);
 
        // create linked list2 8.2.5.3
        head2 = push(head2, 3);
        head2 = push(head2, 5);
        head2 = push(head2, 2);
        head2 = push(head2, 8);
 
        var x = 10;
 
        document.write("Count = " + countPairs(head1, head2, x));
 
// This code contributed by umadevi9616
</script>
 
 
Output
Count = 1

Time complexity: O(N^2)

Auxiliary Space: O(1)



Next Article
Two nodes in a Linked list whose product is equal to the target value

V

VishalBachchas
Improve
Article Tags :
  • DSA
  • Linked List
  • Data Structures-Linked List
  • Technical Scripter 2018
Practice Tags :
  • Linked List

Similar Reads

  • Count pairs from two linked lists whose sum is equal to a given value
    Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements. Given a value x. The problem is to count all pairs from both lists whose sum is equal to the given value x. Note: The pair has an element from each linked list. Examples: Input : list1 = 3->1->5->7 lis
    15+ min read
  • Count pairs from two BSTs whose sum is equal to a given value x
    Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The task is to count all pairs from both the BSTs whose sum is equal to x. Examples: Input : Output: 3Explanation: The pairs are: (5, 11), (6, 10) and (8, 8) whose sum is equal to x. Table of Content [Naive Approach] U
    15 min read
  • Count pairs from two sorted arrays whose sum is equal to a given value x
    Given two sorted arrays of size m and n of distinct elements. Given a value x. The problem is to count all pairs from both arrays whose sum is equal to x. Note: The pair has an element from each array.Examples : Input : arr1[] = {1, 3, 5, 7} arr2[] = {2, 3, 5, 8} x = 10 Output : 2 The pairs are: (5,
    15+ min read
  • Count of Nodes in a LinkedList whose value is equal to their frequency
    Given a Singly linked list, the task is to count the number of nodes whose data value is equal to its frequency. Examples: Input: Linked list = 2 -> 3 -> 3 -> 3 -> 4 -> 2 Output: 2 Frequency of element 2 is 2 Frequency of element 3 is 3 Frequency of element 4 is 1 So, 2 and 3 are elem
    7 min read
  • Two nodes in a Linked list whose product is equal to the target value
    Given a head of a singly linked list and a target value. The task is to find whether there exist any two nodes in the linked list whose product is equal to the target value. Examples: Input: Linked-List = 2->5->3->4->6, Target = 12Output: True Input: Linked-List = 1->4->3->7-
    5 min read
  • Count pairs from a given array whose product lies in a given range
    Given an array arr[] of size N, and integers L and R, the task is to count the number of pairs [arri , arrj] such that i < j and the product of arr[i] * arr[j] lies in the given range [L, R], i.e. L ? arr[i] * arr[j] ? R. Examples: Input: arr[ ] = {4, 1, 2, 5}, L = 4, R = 9Output: 3Explanation: V
    13 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 <=> 2 <=> 4 <=> 5 <=> 6 <=> 8 <=> 9 x = 8 Output
    10 min read
  • Count triplets in a sorted doubly linked list whose sum is equal to a given value x
    Given a sorted doubly linked list of distinct nodes and a value x. The task is to count the number of triplets in the list that sum up to a given value x. Examples: Input: Output: 0Explanation: No triplets are present in the above linked list that sum up to a given value x. Input: Output: 1Explanati
    15+ min read
  • Count pairs in a sorted array whose product is less than k
    Given a sorted integer array and number k, the task is to count pairs in an array whose product is less than x. Examples: Input: A = {2, 3, 5, 6}, k = 16 Output: 4 Pairs having product less than 16: (2, 3), (2, 5), (2, 6), (3, 5) Input: A = {2, 3, 4, 6, 9}, k = 20 Output: 6 Pairs having product less
    12 min read
  • Count of equal value pairs from given two Arrays such that a[i] equals b[j]
    Given two arrays a[] and b[] of length N and M respectively, sorted in non-decreasing order. The task is to find the number of pairs (i, j) such that, a[i] equals b[j]. Examples: Input: a[] = {1, 1, 3, 3, 3, 5, 8, 8}, b[] = {1, 3, 3, 4, 5, 5, 5}Output: 11Explanation: Following are the 11 pairs with
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences