×

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

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

In this problem, we have given two linked lists of size n1 and n2 with distinct elements and a value k. We need to count all pairs from both lists whose sum is equal to the value k.

Note: The pair has an element from each linked list.

Examples:

Input: list1 = 3 ->1 ->5 ->7

 list2 = 8 ->2 ->5 ->3k = 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->12k = 9        

Output: 5

Method 1:(Naive Approach)

In this method, we will use two loops to pick elements from both the linked lists and check whether the sum of the pair is equal to x or not.

C implementation to count pairs from both linked lists whose sum is equal to a given value

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start1 = NULL, * start2 = NULL, * res = NULL;
 intlen = 0, n;
 // For inserting the elements in the linked list
 void add(int item, struct node ** temp)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(*temp == NULL)
 {
 * temp = t;
 (* temp) ->info = item;
 (* temp) ->next = NULL;
 return;
 }
 else
 {
 struct node * p = * temp;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For counting pairs from two linked lists whose sum is equal to a given value
 intcountPairs(struct node * head1, struct node *  head2, int k)
 {
 int count = 0;
 struct node * t1, * t2;
     // traverse the 1st linked list
 for (t1 = head1; t1 != NULL; t1 = t1 -> next)
 for (t2 = head2; t2 != NULL; t2 = t2 -> next)
 if ((t1 -> info + t2 -> info) == k)
 count++;
 return count;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
 }
 while(t -> next != NULL)
 {
                         printf("%d -> ", t -> info);
                         t = t -> next;
 }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 int k;
 printf("Enter the value of k:");
 scanf("%d", &k);
 // Add element into the linked1
 add(4, &start1);
 add(3, &start1);
 add(5, &start1);
 add(6, &start1);
 add(9, &start1);
 add(8, &start1);
 // Add element into the linked2
 add(1, &start2);
 add(4, &start2);
 add(3, &start2);
 add(7, &start2);
 add(9, &start2);
 add(2, &start2);
 int res = countPairs(start1, start2, k);
 printf("count is:%d",res);
 return 0;
 } 

Output:

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

Time Complexity: The time complexity of the above method is O(n1*n2).

Space Complexity:The space complexity of the above method is O(1) which is constant.

Method 2:(By Sorting)

This method will sort the 1st linked list in ascending order and the 2nd linked list in descending order. Then, we will traverse both the linked lists from left to right to count the pairs.

Note:Here, we assume that we have sorted linked lists.

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start1 = NULL, * start2 = NULL, * res = NULL;
 intlen = 0, n;
 // For inserting the elements in the linked list
 void add(int item, struct node ** temp)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(*temp == NULL)
 {
 * temp = t;
 (* temp) ->info = item;
 (* temp) ->next = NULL;
 return;
 }
 else
 {
 struct node * p = * temp;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // For counting pairs from two linked lists whose sum is equal to a given value
 intcountPairs(struct node * head1, struct node *  head2, int k)
 {
 int count = 0;
 while (head1 != NULL && head2 != NULL)
     {
 if ((head1->data + head2->data) == x)
         {
             head1 = head1->next;
             head2 = head2->next;
 count++;   
         }   
 else if ((head1->data + head2->data)> x)
             head2 = head2->next;
 else
             head1 = head1 ->next;
     }       
 return count;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
 }
 while(t -> next != NULL)
 {
                         printf("%d -> ", t -> info);
                         t = t -> next;
 }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 int k;
 printf("Enter the value of k:");
 scanf("%d", &k);
 // Add element into the linked1
 add(3, &start1);
 add(4, &start1);
 add(5, &start1);
 add(6, &start1);
 add(8, &start1);
 add(9, &start1);
 // Add element into the linked2
 add(9, &start2);
 add(7, &start2);
 add(4, &start2);
 add(3, &start2);
 add(2, &start2);
 add(1, &start2);
 int res = countPairs(start1, start2, k);
 printf("count is:%d",res);
 return 0;
 } 

Output:

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

Time Complexity: The time complexity of above method is O(n1 *  logn1) +.O(n2 *  logn2).

Space Complexity:The space complexity of the above method is O(1) which is constant.


Related Topics

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

7 minutes read.

Cycle sort

Cycle sort is an examination arranging calculation which powers exhibit to be figured into the quantity of cycles where every one of them can be pivoted to create an arranged...

5 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Function to Delete a Leaf Node from a Binary Tree

Implementation // We are writing a C++ code to eliminate all the leaves from the given value.  #include <bits/stdc++.h> using namespace std; // creating a new binary tree node struct __nod { int record; struct __nod *Lft,...

4 minutes read.

AVL tree in data structure c++

AVL tree is generally known as the self-sustained and most balanced tree in the field of a binary search tree. It was also widely known as the height-balanced binary tree....

6 minutes read.

Operations of B++ tree

Insertion When we discuss the insertion operation in the B++ tree, this operation helps us in pushing a new element in the tree at any given place. In this case, the...

17 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

What is a full Binary Tree?

A full binary tree is considered to be a special kind of binary tree in which every single node or leaf node present either contains two children or no children...

4 minutes read.