# 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
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: Please try your approach on {IDE} first, before moving on to the solution.

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.

## C/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 */

/* move the head to point to the new node */
}

// function to count all pairs from both the linked lists
// whose sum is equal to a given value
{
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()
{

int x = 10;

cout << "Count = "
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

import java.util.Arrays;
import java.util.Iterator;

class GFG
{
// method to count all pairs from both the linked lists
// whose sum is equal to a given value
{
int count = 0;

// traverse the 1st linked list
while(itr1.hasNext())
{
// for each node of 1st list
// traverse the 2nd list

while(itr2.hasNext())
{
// if sum of pair is equal to 'x'
// increment count
if ((itr1.next() + 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};

int x = 10;

}
}
```

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 list != 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.

## C/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 */

/* move the head to point to the new node */
}

// function to count all pairs from both the linked
// lists whose sum is equal to a given value
int x)
{
int count = 0;

// sort head1 in ascending order and
// For simplicity both lists are considered to be
// sorted in the respective orders

// traverse both the lists from left to right
{
// if this sum is equal to 'x', then move both
// the lists to next nodes and increment 'count'
{
count++;
}

// if this sum is greater than x, then
// move head2 to next node

// else move head1 to next node
else
}

// required count of pairs
return count;
}

// Driver program to test above
int main()
{

// assumed to be in ascending order

// assumed to be in descending order

int x = 10;

cout << "Count = "
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

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;

class GFG
{
// method to count all pairs from both the linked lists
// whose sum is equal to a given value
{
int count = 0;

// sort head1 in ascending order and

// traverse both the lists from left to right

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};

int x = 10;

}
}
```

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.

## 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 */

/* move the head to point to the new node */
}

// function to count all pairs from both the linked
// lists whose sum is equal to a given value
int x)
{
int count = 0;

unordered_set<int> us;

// insert all the elements of 1st list
// in the hash table(unordered_set 'us')
{

// move to next node
}

// for each element of 2nd list
{
// find (x - head2->data) in 'us'
if (us.find(x - head2->data) != us.end())
count++;

// move to next node
}
// required count of pairs
return count;
}

// Driver program to test above
int main()
{

int x = 10;

cout << "Count = "
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

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;

class GFG
{
// method to count all pairs from both the linked lists
// whose sum is equal to a given value
{
int count = 0;

HashSet<Integer> us = new HashSet<Integer>();

// insert all the elements of 1st list
// in the hash table(unordered_set 'us')
while (itr1.hasNext())
{

}

// for each element of 2nd list
while (itr2.hasNext())
{
// find (x - head2->data) in 'us'
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};

int x = 10;

}
}
```

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.

This article is contributed by Ayush Jauhari. 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.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
2.1 Average Difficulty : 2.1/5.0
Based on 6 vote(s)