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 Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count pairs in a binary tree whose sum is equal to a given value x
Next article icon

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

Last Updated : 01 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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         list2 = 8->2->5->3         x = 10 Output : 2 The pairs are: (5, 5) and (7, 3)  Input : list1 = 4->3->5->7->11->2->1         list2 = 2->3->4->5->6->8-12         x = 9          Output : 5
Recommended Practice
Count Pairs whose sum is equal to X
Try It!

Method 1 (Naive Approach): Using two loops pick elements from both the linked lists and check whether the sum of the pair is equal to x or not.

 

Implementation:

C++




// C++ implementation to count pairs from both linked
// lists  whose sum is equal to a given value
#include <bits/stdc++.h>
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 sum 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 program to test above
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 implementation to count pairs from both linked
// lists  whose sum is equal to a given value
 
// Note : here we use java.util.LinkedList for
// linked list implementation
 
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
 
class GFG
{
    // method to count all pairs from both the linked lists
    // whose sum is equal to a given value
    static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x)
    {
        int count = 0;
          
        // traverse the 1st linked list
        Iterator<Integer> itr1 = head1.iterator();
        while(itr1.hasNext())
        {
            // for each node of 1st list
            // traverse the 2nd list
            Iterator<Integer> itr2 = head2.iterator();
            Integer t = itr1.next();
            while(itr2.hasNext())
            {
                // if sum of pair is equal to 'x'
                // increment count
                if ((t + itr2.next()) == x)
                    count++;
            }
        }
                            
        // required count of pairs    
        return count;
    }
     
    // Driver method
    public static void main(String[] args)
    {
        Integer arr1[] = {3, 1, 5, 7};
        Integer arr2[] = {8, 2, 5, 3};
         
        // create linked list1 3->1->5->7
        LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1));
         
        // create linked list2 8->2->5->3
        LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2));
        
        int x = 10;
          
        System.out.println("Count = " + countPairs(head1, head2, x));
    }   
}
 
 

Python3




# Python3 implementation to count pairs from both linked
# lists whose sum 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):
    new_node=Node(new_data)
    #new_node.data = new_data
    new_node.next = head_ref
    head_ref = new_node
    return head_ref
 
 
# function to count all pairs from both the linked lists
# whose sum is equal to a given value
def countPairs(head1, head2, x):
    count = 0
     
    #struct Node p1, p2
     
    # traverse the 1st linked list
    p1 = head1
    while(p1 != None):
 
        # for each node of 1st list
        # traverse the 2nd list
        p2 = head2
        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 program to test above
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 = ",countPairs(head1, head2, x))
     
# This code is contributed by AbhiThakur
 
 

C#




// C# implementation to count pairs from both linked
// lists whose sum is equal to a given value
using System;
using System.Collections.Generic;
     
 
// Note : here we use using System.Collections.Generic for
// linked list implementation
class GFG
{
    // method to count all pairs from both the linked lists
    // whose sum is equal to a given value
    static int countPairs(List<int> head1, List<int> head2, int x)
    {
        int count = 0;
         
        // traverse the 1st linked list
         
        foreach(int itr1 in head1)
        {
            // for each node of 1st list
            // traverse the 2nd list
            int t = itr1;
            foreach(int itr2 in head2)
            {
                // if sum of pair is equal to 'x'
                // increment count
                if ((t + itr2) == x)
                    count++;
            }
        }
                             
        // required count of pairs    
        return count;
    }
     
    // Driver code
    public static void Main(String []args)
    {
        int []arr1 = {3, 1, 5, 7};
        int []arr2 = {8, 2, 5, 3};
         
        // create linked list1 3->1->5->7
        List<int> head1 = new List<int>(arr1);
         
        // create linked list2 8->2->5->3
        List<int> head2 = new List<int>(arr2);
         
        int x = 10;
         
    Console.WriteLine("Count = " + countPairs(head1, head2, x));
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// javascript implementation to count pairs from both linked
// lists  whose sum is equal to a given value
 
// Note : here we use java.util.LinkedList for
// linked list implementation
    // method to count all pairs from both the linked lists
    // whose sum is equal to a given value
    function countPairs( head1, head2 , x) {
        var count = 0;
 
        // traverse the 1st linked list
         
        for (var itr1 of head1) {
            // for each node of 1st list
            // traverse the 2nd list
             
            for (var itr2 of head2) {
                // if sum of pair is equal to 'x'
                // increment count
                if ((itr1 + itr2) == x)
                    count++;
            }
        }
 
        // required count of pairs
        return count;
    }
 
    // Driver method
     
        var arr1 = [ 3, 1, 5, 7 ];
        var arr2 = [ 8, 2, 5, 3 ];
 
        // create linked list1 3->1->5->7
        var head1 = (arr1);
 
        // create linked list2 8->2->5->3
        var head2 = arr2;
 
        var x = 10;
 
        document.write("Count = " + countPairs(head1, head2, x));
 
// This code is contributed by Rajput-Ji
</script>
 
 
Output
Count = 2

Time Complexity: O(n1*n2) 
Auxiliary Space: O(1)
 
Method 2 (Sorting): Sort the 1st linked list in ascending order and the 2nd linked list in descending order using merge sort technique. Now traverse both the lists from left to right in the following way:

Algorithm: 

countPairs(list1, list2, x)   Initialize count = 0   while list1 != NULL and list2 != NULL      if (list1->data + list2->data) == x         list1 = list1->next             list2 = list2->next         count++     else if (list1->data + list2->data) > x         list2 = list2->next     else         list1 = list1->next    return count     

For simplicity, the implementation given below assumes that list1 is sorted in ascending order and list2 is sorted in descending order.

Implementation:

C++




// C++ implementation to count pairs from both linked
// lists  whose sum is equal to a given value
#include <bits/stdc++.h>
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 sum is equal to a given value
int countPairs(struct Node* head1, struct Node* head2,
                                              int x)
{
    int count = 0;
     
    // sort head1 in ascending order and
    // head2 in descending order
    // sort (head1), sort (head2)
    // For simplicity both lists are considered to be
    // sorted in the respective orders
     
    // traverse both the lists from left to right
    while (head1 != NULL && head2 != NULL)
    {
        // if this sum is equal to 'x', then move both
        // the lists to next nodes and increment 'count'
        if ((head1->data + head2->data) == x)
        {
            head1 = head1->next;
            head2 = head2->next;
            count++;   
        }   
         
        // if this sum is greater than x, then
        // move head2 to next node
        else if ((head1->data + head2->data) > x)
            head2 = head2->next;
             
        // else move head1 to next node   
        else
            head1 = head1->next;
    }       
         
    // required count of pairs    
    return count;
}
 
// Driver program to test above
int main()
{
    struct Node* head1 = NULL;
    struct Node* head2 = NULL;
     
    // create linked list1 1->3->5->7
    // assumed to be in ascending order
    push(&head1, 7);
    push(&head1, 5);
    push(&head1, 3);
    push(&head1, 1);   
     
    // create linked list2 8->5->3->2
    // assumed to be in descending order
    push(&head2, 2);
    push(&head2, 3);
    push(&head2, 5);
    push(&head2, 8);
     
    int x = 10;
     
    cout << "Count = "
         << countPairs(head1, head2, x);
    return 0;
}
 
 

Java




// Java implementation to count pairs from both linked
// lists  whose sum is equal to a given value
 
// Note : here we use java.util.LinkedList for
// linked list implementation
 
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
 
class GFG
{
    // method to count all pairs from both the linked lists
    // whose sum is equal to a given value
    static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x)
    {
        int count = 0;
          
        // sort head1 in ascending order and
        // head2 in descending order
        Collections.sort(head1);
        Collections.sort(head2,Collections.reverseOrder());
         
        // traverse both the lists from left to right
        Iterator<Integer> itr1 = head1.iterator();
        Iterator<Integer> itr2 = head2.iterator();
         
        Integer num1 = itr1.hasNext() ? itr1.next() : null;
        Integer num2 = itr2.hasNext() ? itr2.next() : null;
         
        while(num1 != null && num2 != null)
        {    
             
            // if this sum is equal to 'x', then move both
            // the lists to next nodes and increment 'count'
             
            if ((num1 + num2) == x)
            {
                num1 = itr1.hasNext() ? itr1.next() : null;
                num2 = itr2.hasNext() ? itr2.next() : null;
                 
                count++;
            }
             
            // if this sum is greater than x, then
            // move itr2 to next node
            else if ((num1 + num2) > x)
                num2 = itr2.hasNext() ? itr2.next() : null;
             
            // else move itr1 to next node
            else
                num1 = itr1.hasNext() ? itr1.next() : null;
             
        }
                            
        // required count of pairs    
        return count;
    }
     
    // Driver method
    public static void main(String[] args)
    {
        Integer arr1[] = {3, 1, 5, 7};
        Integer arr2[] = {8, 2, 5, 3};
         
        // create linked list1 3->1->5->7
        LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1));
         
        // create linked list2 8->2->5->3
        LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2));
        
        int x = 10;
          
        System.out.println("Count = " + countPairs(head1, head2, x));
    }   
}
 
 

Python3




# Python implementation to count pairs from both linked
# lists whose sum 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)
   
    # 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 sum is equal to a given value
def countPairs(head1, head2, x):
    count = 0
   
    # sort head1 in ascending order and
    # head2 in descending order
    # sort (head1), sort (head2)
    # For simplicity both lists are considered to be
    # sorted in the respective orders
   
    # traverse both the lists from left to right
    while head1 is not None and head2 is not None:
        # if this sum is equal to 'x', then move both
        # the lists to next nodes and increment 'count'
        if (head1.data + head2.data) == x:
            head1 = head1.next
            head2 = head2.next
            count += 1
           
        # if this sum is greater than x, then
        # move head2 to next node
        elif (head1.data + head2.data) > x:
            head2 = head2.next
           
        # else move head1 to next node   
        else:
            head1 = head1.next
       
    # required count of pairs    
    return count
   
# Driver program to test above
if __name__=='__main__':
    head1 = None
    head2 = None
   
    # create linked list1 1->3->5->7
    # assumed to be in ascending order
    head1 = push(head1, 7)
    head1 = push(head1, 5)
    head1 = push(head1, 3)
    head1 = push(head1, 1)
       
    # create linked list2 8->5->3->2
    # assumed to be in descending order
    head2 = push(head2, 2)
    head2 = push(head2, 3)
    head2 = push(head2, 5)
    head2 = push(head2, 8)
   
    x = 10
       
    print("Count =", countPairs(head1, head2, x))
     
# This code is contributed by Aditya Sharma
 
 

Javascript




// JavaScript implementation to count pairs from both linked
// lists whose sum is equal to a given value
 
// A Linked List Node
class Node{
    constructor(data){
        this.data = data;
        this.next = null;
    }
}
 
// Function to insert a node at the
// beginning o the linked list
function push(head_ref, new_data){
    // allocate node and put in the data
    let new_node = new Node(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 sum is equal to a given value
function countPairs(head1, head2, x){
    let count = 0;
     
    // sort head1 in ascending order and
    // head2 in descending order
    // sort (head1), sort (head2)
    // For simplicity both lists are considered to be
    // sorted in the respective orders
       
    // traverse both the lists from left to right
    while(head1 != null && head2 != null){
        // if this sum is equal to 'x', then move both
        // the lists to next nodes and increment 'count'
        if(head1.data + head2.data == x){
            head1 = head1.next;
            head2 = head2.next;
            count++;
        }
        // if this sum is greater than x, then
        // move head2 to next node
        else if(head1.data + head2.data > x)
            head2 = head2.next;
         
        // else move head1 to next node
        else
            head1 = head1.next;
     
    // required count of pairs
    }
    return count;
}
 
// Driver program to test above
let head1 = null;
let head2 = null;
 
// create linked list1 1->3->5->7
// assumed to be in ascending order
head1 = push(head1, 7);
head1 = push(head1, 5);
head1 = push(head1, 3);
head1 = push(head1, 1);
 
// create linked list2 8->5->3->2
// assumed to be in descending order
head2 = push(head2, 2);
head2 = push(head2, 3);
head2 = push(head2, 5);
head2 = push(head2, 8);
 
let x = 10;
console.log("Count = " + countPairs(head1, head2, x));
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)
 
 

C#




// C# implementation to count pairs from both linked
// lists  whose sum is equal to a given value
 
using System;
 
// A Linked list node
class Node
{
    public int data;
    public Node next;
 
    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}
 
class Program
{
    // 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(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 sum is equal to a given value
    static int countPairs(Node head1, Node head2, int x)
    {
        int count = 0;
 
        // sort head1 in ascending order and
        // head2 in descending order
        // sort (head1), sort (head2)
        // For simplicity both lists are considered to be
        // sorted in the respective orders
 
        // traverse both the lists from left to right
        while (head1 != null && head2 != null)
        {
            // if this sum is equal to 'x', then move both
            // the lists to next nodes and increment 'count'
            if ((head1.data + head2.data) == x)
            {
                head1 = head1.next;
                head2 = head2.next;
                count++;
            }
 
            // if this sum is greater than x, then
            // move head2 to next node
            else if ((head1.data + head2.data) > x)
            {
                head2 = head2.next;
            }
 
            // else move head1 to next node   
            else
            {
                head1 = head1.next;
            }
        }
 
        // required count of pairs    
        return count;
    }
 
    // Driver program to test above
    static void Main(string[] args)
    {
        Node head1 = null;
        Node head2 = null;
 
        // create linked list1 1->3->5->7
        // assumed to be in ascending order
        head1 = push(head1, 7);
        head1 = push(head1, 5);
        head1 = push(head1, 3);
        head1 = push(head1, 1);
 
        // create linked list2 8->5->3->2
        // assumed to be in descending order
        head2 = push(head2, 2);
        head2 = push(head2, 3);
        head2 = push(head2, 5);
        head2 = push(head2, 8);
 
        int x = 10;
 
        Console.WriteLine("Count = " + countPairs(head1, head2, x));
    }
}
 
// This code is contributed by sdeadityasharma
 
 
Output
Count = 2

Time Complexity: O(n1*logn1) + O(n2*logn2) 
Auxiliary Space: O(1) 

Sorting will change the order of nodes. If order is important, then copy of the linked lists can be created and used.

Method 3 (Hashing): Hash table is implemented using unordered_set in C++. We store all first linked list elements in hash table. For elements of second linked list, we subtract every element from x and check the result in hash table. If result is present, we increment the count.

Implementation:

C++




// C++ implementation to count pairs from both linked 
// lists whose sum is equal to a given value
#include <bits/stdc++.h>
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 sum is equal to a given value
int countPairs(struct Node* head1, struct Node* head2,
                                               int x)
{
    int count = 0;
     
    unordered_set<int> us;
     
    // insert all the elements of 1st list
    // in the hash table(unordered_set 'us')
    while (head1 != NULL)
    {
        us.insert(head1->data);   
         
        // move to next node   
        head1 = head1->next;
    }
     
    // for each element of 2nd list
    while (head2 != NULL)   
    {
        // find (x - head2->data) in 'us'
        if (us.find(x - head2->data) != us.end())
            count++;
         
        // move to next node
        head2 = head2->next;   
    }
    // required count of pairs    
    return count;
}
 
// Driver program to test above
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 implementation to count pairs from both linked
// lists  whose sum is equal to a given value
 
// Note : here we use java.util.LinkedList for
// linked list implementation
 
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
 
class GFG
{
    // method to count all pairs from both the linked lists
    // whose sum is equal to a given value
    static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x)
    {
        int count = 0;
          
        HashSet<Integer> us = new HashSet<Integer>();
          
        // insert all the elements of 1st list
        // in the hash table(unordered_set 'us')
        Iterator<Integer> itr1 = head1.iterator();
        while (itr1.hasNext())
        {
            us.add(itr1.next());   
            
        }
         
        Iterator<Integer> itr2 = head2.iterator();
        // for each element of 2nd list
        while (itr2.hasNext())   
        {
            // find (x - head2->data) in 'us'
            if (!(us.add(x - itr2.next())))
                count++;
                
        }
         
        // required count of pairs    
        return count;
    }
     
    // Driver method
    public static void main(String[] args)
    {
        Integer arr1[] = {3, 1, 5, 7};
        Integer arr2[] = {8, 2, 5, 3};
         
        // create linked list1 3->1->5->7
        LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1));
         
        // create linked list2 8->2->5->3
        LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2));
        
        int x = 10;
          
        System.out.println("Count = " + countPairs(head1, head2, x));
    }   
}
 
 

Python3




# Python3 implementation to count pairs from both linked 
# lists whose sum is equal to a given value
  
''' A Linked list node '''
class Node:
     
    def __init__(self):
        self.data = 0
        self.next = None
   
# function to add a node at the
# beginning of the linked list
def push(head_ref, new_data):
 
  ''' allocate node '''
  new_node =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 sum is equal to a given value
def countPairs(head1, head2, x):
    count = 0;   
    us = set()
      
    # add all the elements of 1st list
    # in the hash table(unordered_set 'us')
    while (head1 != None):  
        us.add(head1.data);   
          
        # move to next node   
        head1 = head1.next;
      
    # for each element of 2nd list
    while (head2 != None): 
     
        # find (x - head2.data) in 'us'
        if ((x - head2.data) in us):
            count += 1
          
        # move to next node
        head2 = head2.next;   
     
    # required count of pairs    
    return count;
  
# Driver program to test above
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 =", countPairs(head1, head2, x));
     
# This code is contributed by rutvik_56
 
 

C#




// C# implementation to count pairs from both linked
// lists whose sum is equal to a given value
 
// Note : here we use java.util.LinkedList for
// linked list implementation
using System;
using System.Collections.Generic;
 
class GFG
{
    // method to count all pairs from both the linked lists
    // whose sum is equal to a given value
    static int countPairs(List<int> head1, List<int> head2, int x)
    {
        int count = 0;
         
        HashSet<int> us = new HashSet<int>();
         
        // insert all the elements of 1st list
        // in the hash table(unordered_set 'us')
        foreach(int itr1 in head1)
        {
            us.Add(itr1);
             
        }
 
        // for each element of 2nd list
        foreach(int itr2 in head2)
        {
            // find (x - head2->data) in 'us'
            if (!(us.Contains(x - itr2)))
                count++;
                 
        }
         
        // required count of pairs    
        return count;
    }
     
    // Driver code
    public static void Main(String[] args)
    {
        int []arr1 = {3, 1, 5, 7};
        int []arr2 = {8, 2, 5, 3};
         
        // create linked list1 3->1->5->7
        List<int> head1 = new List<int>(arr1);
         
        // create linked list2 8->2->5->3
        List<int> head2 = new List<int>(arr2);
         
        int x = 10;
         
        Console.WriteLine("Count = " + countPairs(head1, head2, x));
    }
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
 
// JavaScript implementation to count pairs
// from both linked lists whose sum is equal
// to a given value
 
// A Linked list node
class Node
{
    constructor(new_data)
    {
        this.data = new_data;
        this.next = null;
    }
};
 
// Function to count all pairs from both the linked
// lists whose sum is equal to a given value
function countPairs(head1, head2, x)
{
    let count = 0;
    let us = new Set();
 
    // Insert all the elements of 1st list
    // in the hash table(unordered_set 'us')
    while (head1 != null)
    {
        us.add(head1.data);
 
        // Move to next node   
        head1 = head1.next;
    }
 
    // For each element of 2nd list
    while (head2 != null)
    {
         
        // Find (x - head2.data) in 'us'
        if (us.has(x - head2.data))
            count++;
 
        // Move to next node
        head2 = head2.next;
    }
     
    // Required count of pairs    
    return count;
}
 
// Driver code
let head1 = null;
let head2 = null;
 
// Create linked list1 3.1.5.7
head1 = new Node(3)
head1.next = new Node(1)
head1.next.next = new Node(5)
head1.next.next.next = new Node(7)
 
// Create linked list2 8.2.5.3
head2 = new Node(8)
head2.next = new Node(2)
head2.next.next = new Node(5)
head2.next.next.next = new Node(3)
 
let x = 10;
 
document.write("Count = " +
               countPairs(head1, head2, x));
                
// This code is contributed by Potta Lokesh
 
</script>
 
 
Output
Count = 2

Time Complexity: O(n1 + n2) 
Auxiliary Space: O(n1), hash table should be created of the array having smaller size so as to reduce the space complexity.

 



Next Article
Count pairs in a binary tree whose sum is equal to a given value x

A

Ayush Jauhari
Improve
Article Tags :
  • DSA
  • Hash
  • Linked List
  • Sorting
Practice Tags :
  • Hash
  • Linked List
  • Sorting

Similar Reads

  • Count pairs from two linked lists whose product 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 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-
    8 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 pairs in a binary tree whose sum is equal to a given value x
    Given a binary tree containing n distinct numbers and a value x. The problem is to count pairs in the given binary tree whose sum is equal to the given value x. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 x = 10 Output : 3 The pairs are (3, 7), (2, 8) and (4, 6). 1) Naive Approach: One by one get ea
    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
  • 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
  • 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
  • Find a triplet from three linked lists with sum equal to a given number
    Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8, and 90->20->59, and the given number is 101, the output should be triple "
    14 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
  • Count pairs from two arrays having sum equal to K
    Given an integer K and two arrays A1 and A2, the task is to return the total number of pairs (one element from A1 and one element from A2) with a sum equal to K. Note: Arrays can have duplicate elements. We consider every pair as different, the only constraint is, an element (of any array) can parti
    6 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